从此XML文件中提取数据的最有效方法

Jas*_*ine 2 python xml parsing lxml elementtree

XML文件示例

<GateDocument> 
  <GateDocumentFeatures>
    ...
  </GateDocumentFeatures>
  <TextWithNodes>
    <Node id="0"/>
    MESSAGE SET
    <Node id="19"/> 
    <Node id="20"/>
    1. 1/1/09 - sample text 1
    <Node id="212"/>
    sample text 2
    <Node id="223"/>
    sample text 3
    ...
    <Node id="160652"/>
  </TextWithNodes>
  <AnnotationSet></AnnotationSet>
  <AnnotationSet Name="SomeName">
    ...
  </AnnotationSet>
</GateDocument>
Run Code Online (Sandbox Code Playgroud)

刚开始,这是我第一次用Python编写代码并处理XML,很抱歉,如果我错过了非常明显的事情!

我的目标是在特定节点ID处提取示例文本.

第一次尝试 - 我使用了minidom,因为这个没有给我正确的方法来处理提取(http://stackoverflow.com/questions/11122736/extracting-text-from-xml-node-with-minidom)自闭标签中节点ID的奇怪格式.

第二次尝试 - 我在查看lxml时接受了建议,我已成功将文本提取为以下内容:

['\n\t\t','n\t\tMESSAGE SET\n\t\t','\n\t\t','\n\t\t1. 1/1/09 - sample text 1,....,'\n\t']
Run Code Online (Sandbox Code Playgroud)

通过一些清理,我认为我可以使文本正常,但是,我丢失了相关的节点id值.

用代码:

from lxml import etree
from StringIO import StringIO
xmlfile = ('C:\...AnnotationsXML.xml')
xmldoc = etree.parse(xmlfile)  
print xmldoc.xpath("//TextWithNodes/text()")
Run Code Online (Sandbox Code Playgroud)

所以我想我的问题是:

  1. 有没有办法在没有\n\t\t的情况下提取上述内容?我读到它是空间格式化(即标签),但我不知道它<Node id = 0>去了哪里.
  2. 在提取此文件时,是否有更好或更有效的方法?

谢谢!

Lev*_*sky 7

In [1]: from lxml import etree

In [2]: tree = etree.parse('awful.xml')

In [3]: data = {int(node.attrib['id']): node.tail.strip()
   ...: for node in tree.xpath('//TextWithNodes/Node') if node.tail.strip()}

In [4]: data
Out[4]: 
{0: 'MESSAGE SET',
 20: '1. 1/1/09 - sample text 1',
 212: 'sample text 2',
 223: 'sample text 3'}
Run Code Online (Sandbox Code Playgroud)

strip用来摆脱喜欢的东西,\t\ntail在标签后取文字.