Beautifulsoup使用名称空间搜索属性



我想在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。但是,它给了很多命名空间问题。

这是一个简单的答案,但它不清楚您要做什么,或者您可能在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) 

最新更新