繁体   English   中英

无法使用elementtree解析graphml文件

[英]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代码

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

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

如果我从graphml标签中删除属性,那么它可以工作,返回元素

您将获得一个空列表,因为XML文档中没有简单的graph元素。 您的文档具有默认的XML命名空间( http://graphml.graphdrawing.org/xmlns ),因此文档中没有显式名称空间前缀的任何元素都在该命名空间中。

这意味着在要求元素时,您需要提供名称空间信息以及标记名称。 例如:

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

LXML文档有一个关于使用命名空间的部分。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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