user2667397
user2667397

Reputation: 33

To get the child nodes of a parent node in an xml file using python

my xml file goes like this :

<?xml version="1.0" encoding="UTF-8" ?> 
<raml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="raml21.xsd">
<cmData type="actual" scope="all" name="plan_file">
<header>
 <log dateTime="2011-05-18T04:05:02" action="created" /> 
</header>
<managedObject class="SAAL" distName="FGW-74/HNBGW-1/SAAL-1" operation="update">
 <p name="SigN1">100</p> 
 <p name="MaxCc">4</p> 
 <p name="MaxPd">99</p> 
 <p name="MaxStat">67</p> 
 <p name="TimerCc">200</p> 
 <p name="TimerIdle">100</p> 
 <p name="TimerKeepAlive">100</p> 
 <p name="TimerNoResponse">1500</p> 
 <p name="TimerPoll">100</p> 
</managedObject>
</cmData>
</raml>

i need to get all the child nodes under the class 'SAAL' to another array. i am using python version 3.

thanks for ur help in advance.

Upvotes: 0

Views: 480

Answers (2)

falsetru
falsetru

Reputation: 369424

Using xml.etree.ElementTree:

import xml.etree.ElementTree as ET

root = ET.fromstring('''<?xml version="1.0" encoding="UTF-8" ?> 
<raml ...
</raml>''')
child_nodes = root.findall('.//*[@class="SAAL"]/*')
print(child_nodes)

[<Element 'p' at 0x0000000002B01C78>,
 <Element 'p' at 0x0000000002B01CC8>,
 <Element 'p' at 0x0000000002B01D18>,
 <Element 'p' at 0x0000000002B01D68>,
 <Element 'p' at 0x0000000002B01DB8>,
 <Element 'p' at 0x0000000002B01E08>,
 <Element 'p' at 0x0000000002B01E58>,
 <Element 'p' at 0x0000000002B01EA8>,
 <Element 'p' at 0x0000000002B01EF8>]

Upvotes: 0

theodox
theodox

Reputation: 12218

You want to use the elementTree module or one of it's derivatives for this.

Upvotes: 1

Related Questions