我有一个这样的 XML 文档:
I have an XML document which reads like this:
<xml>
<web:Web>
<web:Total>4000</web:Total>
<web:Offset>0</web:Offset>
</web:Web>
</xml>
我的问题是如何使用 Python 中的 BeautifulSoup 之类的库来访问它们?
my question is how do I access them using a library like BeautifulSoup in python?
xmlDom.web["Web"].Total ?不工作?
xmlDom.web["Web"].Total ? does not work?
BeautifulSoup is't 一个 DOM 库本身(它不实现 DOM API).更复杂的是,您在该 xml 片段中使用命名空间.要解析特定的 XML,您可以使用 BeautifulSoup,如下所示:
BeautifulSoup isn't a DOM library per se (it doesn't implement the DOM APIs). To make matters more complicated, you're using namespaces in that xml fragment. To parse that specific piece of XML, you'd use BeautifulSoup as follows:
from BeautifulSoup import BeautifulSoup
xml = """<xml>
<web:Web>
<web:Total>4000</web:Total>
<web:Offset>0</web:Offset>
</web:Web>
</xml>"""
doc = BeautifulSoup( xml )
print doc.find( 'web:total' ).string
print doc.find( 'web:offset' ).string
如果您不使用命名空间,代码可能如下所示:
If you weren't using namespaces, the code could look like this:
from BeautifulSoup import BeautifulSoup
xml = """<xml>
<Web>
<Total>4000</Total>
<Offset>0</Offset>
</Web>
</xml>"""
doc = BeautifulSoup( xml )
print doc.xml.web.total.string
print doc.xml.web.offset.string
这里的关键是 BeautifulSoup 对命名空间一无所知(或关心).因此 web:Web 被视为 web:web 标记,而不是属于 ewebWeb 标记> 命名空间.虽然 BeautifulSoup 将 web:web 添加到 xml 元素字典中,但 python 语法不会将 web:web 识别为单个标识符.
The key here is that BeautifulSoup doesn't know (or care) anything about namespaces. Thus web:Web is treated like a web:web tag instead of as a Web tag belonging to th eweb namespace. While BeautifulSoup adds web:web to the xml element dictionary, python syntax doesn't recognize web:web as a single identifier.
您可以通过阅读文档了解更多信息.
You can learn more about it by reading the documentation.
这篇关于如何使用 BeautifulSoup 访问命名空间的 XML 元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
使用 python 解析非常大的 xml 文件时出现问题Troubles while parsing with python very large xml file(使用 python 解析非常大的 xml 文件时出现问题)
使用 Python 2 在 XML 中按属性查找所有节点Find all nodes by attribute in XML using Python 2(使用 Python 2 在 XML 中按属性查找所有节点)
Python - 如何解析 xml 响应并将元素值存储在变量中Python - How to parse xml response and store a elements value in a variable?(Python - 如何解析 xml 响应并将元素值存储在变量中?)
如何在 Python 中获取 XML 标记值How to get XML tag value in Python(如何在 Python 中获取 XML 标记值)
如何使用 ElementTree 正确解析 utf-8 xml?How to correctly parse utf-8 xml with ElementTree?(如何使用 ElementTree 正确解析 utf-8 xml?)
将 XML 从 URL 解析为 python 对象Parse XML from URL into python object(将 XML 从 URL 解析为 python 对象)