Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get specific nodes in xml file with python

Tags:

python

xml

im searching for a way to get a specific tags .. from a very big xml document with python dom built in module
for example :

<AssetType longname="characters" shortname="chr" shortnames="chrs">
  <type>
    pub
  </type>
  <type>
    geo
  </type>
  <type>
    rig
  </type>
</AssetType>

<AssetType longname="camera" shortname="cam" shortnames="cams">
  <type>
    cam1
  </type>
  <type>
    cam2
  </type>
  <type>
    cam4
  </type>
</AssetType>

i want to retrieve the value of children of AssetType node who got attribute (longname= "characters" ) to have the result of 'pub','geo','rig'
please put in mind that i have more than 1000 < AssetType> nodes
thanx in advance

like image 435
Moayyad Yaghi Avatar asked Feb 09 '10 16:02

Moayyad Yaghi


1 Answers

Assuming your document is called assets.xml and has the following structure:

<assets>
    <AssetType>
        ...
    </AssetType>
    <AssetType>
        ...
    </AssetType>
</assets>

Then you can do the following:

from xml.etree.ElementTree import ElementTree
tree = ElementTree()
root = tree.parse("assets.xml")
for assetType in root.findall("//AssetType[@longname='characters']"):
    for type in assetType.getchildren():
        print type.text
like image 148
Tendayi Mawushe Avatar answered Sep 28 '22 09:09

Tendayi Mawushe