簡體   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