我有以下XML,我想用Python解析ElementTree:
<rdf:RDF xml:base="http://dbpedia.org/ontology/"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:owl="http://www.w3.org/2002/07/owl#"
xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
xmlns="http://dbpedia.org/ontology/">
<owl:Class rdf:about="http://dbpedia.org/ontology/BasketballLeague">
<rdfs:label xml:lang="en">basketball league</rdfs:label>
<rdfs:comment xml:lang="en">
a group of sports teams that compete against each other
in Basketball
</rdfs:comment>
</owl:Class>
</rdf:RDF>
Run Code Online (Sandbox Code Playgroud)
我想找到所有owl:Class标签,然后提取其中所有rdfs:label实例的值.我使用以下代码:
tree = ET.parse("filename")
root = tree.getroot()
root.findall('owl:Class')
Run Code Online (Sandbox Code Playgroud)
由于命名空间,我收到以下错误.
SyntaxError: prefix 'owl' not found in prefix map
Run Code Online (Sandbox Code Playgroud)
我尝试在http://effbot.org/zone/element-namespaces.htm上阅读该文档,但由于上述XML具有多个嵌套命名空间,因此我仍然无法正常工作.
请告诉我如何更改代码以查找所有owl:Class标签.
我想使用"findall"方法在ElementTree模块中找到源xml文件的一些元素.
但是,源xml文件(test.xml)具有命名空间.我将部分xml文件截断为样本:
<?xml version="1.0" encoding="iso-8859-1"?>
<XML_HEADER xmlns="http://www.test.com">
<TYPE>Updates</TYPE>
<DATE>9/26/2012 10:30:34 AM</DATE>
<COPYRIGHT_NOTICE>All Rights Reserved.</COPYRIGHT_NOTICE>
<LICENSE>newlicense.htm</LICENSE>
<DEAL_LEVEL>
<PAID_OFF>N</PAID_OFF>
</DEAL_LEVEL>
</XML_HEADER>
Run Code Online (Sandbox Code Playgroud)
示例python代码如下:
from xml.etree import ElementTree as ET
tree = ET.parse(r"test.xml")
el1 = tree.findall("DEAL_LEVEL/PAID_OFF") # Return None
el2 = tree.findall("{http://www.test.com}DEAL_LEVEL/{http://www.test.com}PAID_OFF") # Return <Element '{http://www.test.com}DEAL_LEVEL/PAID_OFF' at 0xb78b90>
Run Code Online (Sandbox Code Playgroud)
虽然它可以工作,因为有一个名称空间"{http://www.test.com}",在每个标记前面添加一个名称空间是非常不方便的.
使用"find","findall"等方法时,如何忽略命名空间?
如何通过使用ElementTree访问NS属性?
具有以下内容:
<data xmlns="http://www.foo.net/a" xmlns:a="http://www.foo.net/a" book="1" category="ABS" date="2009-12-22">
Run Code Online (Sandbox Code Playgroud)
当我尝试root.get('xmlns')我回来没有,类别和日期都很好,任何帮助赞赏..
假设我要使用Python修改以下XML ElementTree:
<root xmlns:prefix="URI">
<child company:name="***"/>
...
</root>
Run Code Online (Sandbox Code Playgroud)
我正在对XML文件进行如下修改:
import xml.etree.ElementTree as ET
tree = ET.parse('filename.xml')
# XML modification here
# save the modifications
tree.write('filename.xml')
Run Code Online (Sandbox Code Playgroud)
然后,XML文件如下所示:
<root xmlns:ns0="URI">
<child ns0:name="***"/>
...
</root>
Run Code Online (Sandbox Code Playgroud)
如您所见,namepsace prefix更改为ns0。我知道这里ET.register_namespace()提到的使用。
问题ET.register_namespace()在于:
prefix和URI例如,如果xml看起来像:
<root xmlns="http://uri">
<child name="name">
...
</child>
</root>
Run Code Online (Sandbox Code Playgroud)
它将转换为以下内容:
<ns0:root xmlns:ns0="http://uri">
<ns0:child name="name">
...
</ns0:child>
</ns0:root>
Run Code Online (Sandbox Code Playgroud)
如您所见,默认名称空间更改为ns0。
有什么办法解决这个问题ElementTree吗?