0

I need to parse an xml from the shell. When I send the command

telnet IP_addr port

so from a python script I do:

subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)

where cmd is my command.

I obtain an XML that I have to parse This is my output:

Trying 10.1.6.123...
Connected to 10.1.6.123.
Escape character is '^]'.
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE boost_serialization>
<boost_serialization signature="serialization::archive" version="14">
<g>
        <V>13</V>
        <E>34</E>
        <node>
                <name>172.16.102.116</name>
                <id>172.16.102.116</id>
                <regen_pools>
                        <count>0</count>
                        <item_version>0</item_version>
                </regen_pools>
                <osnr_db>0.000000000e+00</osnr_db>
                <osnr>
                        <count>0</count>
                        <item_version>0</item_version>
                </osnr>
        </node>
....

I have already wrote the code to parse that when it is saved into a file, removing the first three lines.

import xml.etree.ElementTree as ET
tree = ET.parse('topo.xml')
root = tree.getroot()
graph={}
app=[]
for vertex in root.findall('g/node'):
    key = vertex.find('id').text

But the xml is passed as a file. How to do it whitout create a file?

Thanks a lot Silvia

1 Answer 1

1

Instead of saving the XML string to a file directly read it using xml.etree.ElementTree.fromstring

EX:

import xml.etree.ElementTree as ET
tree = ET.ElementTree(ET.fromstring(xmlstring))

Sample Code

xmlData = '''<Tables>
<Table><Claimable>false</Claimable><MinorRev>80601</MinorRev><Operation>530600 ION MILL</Operation><HTNum>162</HTNum><WaferEC>80318</WaferEC><HolderType>HACARR</HolderType><Job>167187008</Job></Table>
<Table><Claimable>false</Claimable><MinorRev>71115</MinorRev><Operation>530600 ION MILL</Operation><Experiment>6794</Experiment><HTNum>162</HTNum><WaferEC>71105</WaferEC><HolderType>HACARR</HolderType><Job>16799006</Job></Table>
</Tables>
'''

import xml.etree.ElementTree as ET
tree = ET.ElementTree(ET.fromstring(xmlData))
root = tree.getroot()
print root
Sign up to request clarification or add additional context in comments.

3 Comments

in your case you have a "variable" that you call xmlData in your python script, if I'm not wrong. What I would like to do is read the xml directly from the shell output - I'm sending the command to "print" the xml from the script with subprocess
@user2907822 from the desc you are stripping the first 3 lines and saving it to a file correct?
no, I've saved the output with telnet ip 8881 |tee namefile.xml and manually removed the first 3 lines

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.