我怎样才能Access中使用BeautifulSoup命名空间的XML元素? [英] How can I access namespaced XML elements using BeautifulSoup?

查看:234
本文介绍了我怎样才能Access中使用BeautifulSoup命名空间的XML元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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>

我的问题是我如何访问它们使用库像BeautifulSoup在Python?

my question is how do I access them using a library like BeautifulSoup in python?

xmlDom.web [网络。总?不工作?

xmlDom.web["Web"].Total ? does not work?

推荐答案

BeautifulSoup 是不是一个DOM库每SE(它没有实现的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

如果你没有使用命名空间,在code可能是这样的:

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不知道(或护理)关于命名空间的任何事情。因此,网​​络:网络被视为一个网​​络:网络标签,而不是作为一个网​​站标记属于前作网​​站命名空间。虽然BeautifulSoup增加网​​络:网络来的XML元素的字典,Python语法不承认网​​络:网络作为一个单一的标识符。

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.

这篇关于我怎样才能Access中使用BeautifulSoup命名空间的XML元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆