как я могу найти текст в xmlns с помощью elementtree

У меня есть этот 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>

Я хочу найти текст «foobar» с помощью elementtree, так как вместо «foobar» может быть любой текст?


person Bengineer    schedule 12.09.2012    source источник


Ответы (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 возвращает текстовое содержимое после конечного тега элемента.

person mzjn    schedule 12.09.2012