beautifulsoup搜索属性与命名空间

时间:2014-05-13 07:44:54

标签: python xml

我想在所有标签中搜索XML文件中的xlink:href属性。我无法用beautifulsoup find_all和正则表达式来完成它。以下是我的XML文件。

<body:document-content>
<style:style style:name="P1" style:family="paragraph" style:parent-style-name="Standard">
  <style:text-properties officeooo:paragraph-rsid="00118689"/>
</style:style>

<body:text>
  <text:sequence-decls>
    <text:sequence-decl text:display-outline-level="0" text:name="Illustration"/>
    <text:sequence-decl text:display-outline-level="0" text:name="Table"/>
  </text:sequence-decls>
  <text:p text:style-name="P1">This is example document</text:p>
  <text:p text:style-name="P1"/>
  <text:p text:style-name="P1">hello world</text:p>
  <text:p text:style-name="P1"/>
  <text:p text:style-name="P1">
    <text:a xlink:type="simple" xlink:href="https://example.com">https://example.com</text:a>
  </text:p>
  <text:p text:style-name="P1"/>
  <text:p text:style-name="P1"/>
</body:text>
</body:document-content>

我想从XML文件中删除以下标记行。

<text:a xlink:type="simple" xlink:href="https://example.com">https://example.com</text:a>

请建议如何使用beautifulsoup完成此操作。我也尝试过Elementtree。但是,它提供了很多名称空间问题。

1 个答案:

答案 0 :(得分:0)

这是一个简单的答案,但目前尚不清楚您要尝试做什么,或者您可能在XML中遇到的变体。如果您不需要使用XPath进行更复杂的操作,则示例中的XML表明您只能搜索text:a元素(唯一具有xlink:href属性的元素) - 如果是确实是你想要摆脱的text:a“行”(元素节点)。

from bs4 import BeautifulSoup

with open('test.xml') as x: # text.xml is the xml from your post
    doc = BeautifulSoup(x)
    #print(doc.find_all( 'text:a' ))  # see that it gets all text:a elements
    [s.extract() for s in doc('text:a')] # extracts text:a elements
    print(doc) 
相关问题