简体   繁体   中英

unable to parse graphml file with elementtree

xml

<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
  <graph id="G" edgedefault="undirected">
    <node id="n0"/>
    <node id="n1"/>
    <edge id="e1" source="n0" target="n1"/>
  </graph>
</graphml>

python code

tree = ET.parse(my_file.xml).getroot()

print tree.findall('graph') # returns []

If I remove the attributes from the graphml tag, then it works, returns the element

You are getting an empty list because there are no simple graph elements in your XML document. Your document has a default XML namespace (of http://graphml.graphdrawing.org/xmlns ), so any elements in the document without an explicit namespace prefix are in that namespace.

This means that when asking for an element, you need to provide namespace information along with the tag name. For example:

>>> tree.findall('{http://graphml.graphdrawing.org/xmlns}graph')
[<Element {http://graphml.graphdrawing.org/xmlns}graph at 0x7f2f3e3cf5f0>]
>>> 

The LXML documentation has a section on working with namespaces .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM