【问题标题】:how can I find text in xmlns with elementtree如何使用 elementtree 在 xmlns 中查找文本
【发布时间】:2012-09-12 05:31:16
【问题描述】:

我有这个 xml:

<office:body>
<office: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-decl text:display-outline-level="0" text:name="Text"/>
<text:sequence-decl text:display-outline-level="0" text:name="Drawing"/>
</text:sequence-decls>
<text:p text:style-name="Standard">
<office:annotation>...</office:annotation>
foobar
</text:p>
</office:text>
</office:body>

我想用 elementtree 找到文本“foobar”,因为“foobar”可以是任何文本?

【问题讨论】:

    标签: python xml xml-namespaces elementtree


    【解决方案1】:

    假设 XML 文档看起来像这样(带有声明的命名空间):

    <office:document-content xmlns:office="http://openoffice.org/2000/office"
                             xmlns:text="http://openoffice.org/2000/text">
    
      <office:body>
        <office: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-decl text:display-outline-level="0" text:name="Text"/>
            <text:sequence-decl text:display-outline-level="0" text:name="Drawing"/>
          </text:sequence-decls>
          <text:p text:style-name="Standard">
            <office:annotation>...</office:annotation>
            foobar
          </text:p>
        </office:text>
      </office:body>
    
    </office:document-content>
    

    然后您可以使用此程序获取“foobar”字符串:

    from xml.etree import ElementTree as ET
    
    root = ET.parse("foobar.xml")
    ann = root.find(".//{http://openoffice.org/2000/office}annotation")
    print ann.tail.strip()
    

    这里使用ElementTree.find()方法查找office:annotation元素,Element.tail属性返回元素结束标签后的文本内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-29
      • 2013-05-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多