【发布时间】:2015-04-20 09:08:01
【问题描述】:
我正在尝试用 Python 解析一个非常丑陋的 XML 文件。我设法很好地融入其中,但在 npdoc 元素它失败了。我做错了什么?
XML:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<npexchange xmlns="http://www.example.com/npexchange/3.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.5">
<article id="123" refType="Article">
<articleparts>
<articlepart id="1234" refType="ArticlePart">
<data>
<npdoc xmlns="http://www.example.com/npdoc/2.1" version="2.1" xml:lang="sv_SE">
<body>
<p>Lorem ipsum some random text here.</p>
<p>
<b>Yes this is HTML markup, and I would like to keep that.</b>
</p>
</body>
<headline>
<p>I am a headline</p>
</headline>
<leadin>
<p>I am some other text</p>
</leadin>
</npdoc>
</data>
</articlepart>
</articleparts>
</article>
</npexchange>
这是我目前的python代码:
from xml.etree.ElementTree import ElementTree
def parse(self):
tree = ElementTree(file=filename)
for item in tree.iter("article"):
articleParts = item.find("articleparts")
for articlepart in articleParts.iter("articlepart"):
data = articlepart.find("data")
npdoc = data.find("npdoc")
id = item.get("id")
headline = npdoc.find("headline").text
leadIn = npdoc.find("leadin").text
body = npdoc.find("body").text
return articles
发生的情况是我取出了 id,但我无法访问 npdoc 元素内的字段。 npdoc 变量设置为 None。
更新: 通过使用 .find() 调用中的命名空间,设法将元素放入变量中。我如何获得价值?由于它是 HTML,因此无法正确显示 .text 属性。
【问题讨论】:
-
预期输出是什么?
-
那不是一个有效的 XML 文档。它没有根元素。
-
预期结果是标题变量中的字符串
<p>I am a headline</p>,以此类推。 -
有一个根元素,现在要编辑它。我的清洁有点激进。
-
这是一个命名空间问题。是否可以为
http://www.example.com/npdoc/2.1命名空间定义像xmlns:n这样的前缀?如果没有这样的前缀,就很难访问这个命名空间下的元素。
标签: python xml parsing xml-parsing