【发布时间】:2014-09-22 04:02:40
【问题描述】:
我有这段文字:
INTRODUCTION
This is a test document for xml.
I need to extract this sentence.
Conclusion
It should hopefully..
I need to extract this sentence. 行是斜体。该文件的 xml 如下所示:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n
<w:document
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
mc:Ignorable="w14 w15 wp14">
<w:body>
<w:p w:rsidR="00470EEF" w:rsidRDefault="00456755">
<w:pPr>
<w:rPr>
<w:b/>
</w:rPr>
</w:pPr>
<w:r w:rsidRPr="00456755">
<w:rPr>
<w:b/>
</w:rPr>
<w:t>INTRODUCTION</w:t>
</w:r>
</w:p>
<w:p w:rsidR="00456755" w:rsidRPr="00B042E3" w:rsidRDefault="00456755">
<w:pPr>
<w:rPr>
<w:color w:val="FFFF00"/>
</w:rPr>
</w:pPr>
<w:r w:rsidRPr="00B042E3">
<w:rPr>
<w:color w:val="FFFF00"/>
</w:rPr>
<w:t>This is a test document for xml.</w:t>
</w:r>
</w:p>
<w:p w:rsidR="00456755" w:rsidRDefault="00E971E1">
<w:r>
<w:rPr>
<w:i/>
</w:rPr>
<w:t>I need to extract this sentence.</w:t>
</w:r>
<w:bookmarkStart w:id="0" w:name="_GoBack"/>
<w:bookmarkEnd w:id="0"/>
</w:p>
<w:p w:rsidR="00456755" w:rsidRDefault="00456755"/>
<w:p w:rsidR="00456755" w:rsidRDefault="00456755">
<w:pPr>
<w:rPr>
<w:b/>
</w:rPr>
</w:pPr>
<w:r w:rsidRPr="00456755">
<w:rPr>
<w:b/>
</w:rPr>
<w:t>Conclusion</w:t>
</w:r>
</w:p>
<w:p w:rsidR="00456755" w:rsidRPr="00456755" w:rsidRDefault="00456755">
<w:r w:rsidRPr="00456755">
<w:t>It should hopefully</w:t>
</w:r>
<w:r>
<w:t>..</w:t>
</w:r>
</w:p>
<w:sectPr w:rsidR="00456755" w:rsidRPr="00456755">
<w:pgSz w:w="11906" w:h="16838"/>
<w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="708" w:footer="708" w:gutter="0"/>
<w:cols w:space="708"/>
<w:docGrid w:linePitch="360"/>
</w:sectPr>
</w:body>
</w:document>
我试过了:
tree = ET.parse(doc_xml)
[b.tag for b in tree.iterfind(".//i")]
上面返回一个空列表。
我已经搜索了很多,但无法弄清楚如何做到这一点,因为文本包含在 <w:i/> 中。我见过这个question,使用 BeautifulSoup 很容易做到这一点。
编辑:这并不完全相关,但这是提取所有文本的 ElementTree 方法。
w = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'
for p in source.findall('.//{' + w + '}p'):
print ''.join(t.text for t in p.findall('.//{' + w + '}t'))
【问题讨论】:
-
你可能需要告诉它使用URI为
"http://schemas.openxmlformats.org/wordprocessingml/2006/main"的命名空间,方法是绑定一个前缀,比如w。 -
是的,我已经这样做了,甚至通过'p'标签和't'标签提取了所有文本..
-
请告诉我们你做了什么。您展示的 Python 并未表明使用任何命名空间。
-
我查看了 xpath 语法,发现这里没有“id”。那么我怎样才能归零到一个特定的标签呢?
-
@LarsH 在 lxml 中是否可能出现上述情况?路径并不总是固定的。遍历整个 xml 并返回与“i”相对应的文本
标签: python xml xpath lxml elementtree