使用lxml Python在非标准XML中解析XPath

时间:2012-02-26 23:00:11

标签: python xml xpath lxml

我正在尝试使用Google专利创建所有专利信息的数据库。到目前为止,我的大部分工作都是在Python to parse non-standard XML file中使用MattH的这个非常好的答案。我的Python太大而无法显示,因此链接的here

源文件are here: 将一堆xml文件附加到一个带有多个头文件的文件中。问题是在解析这个具有多个xml和dtd声明的非常规“非标准”XML文件时尝试使用正确的xpath表达式。我一直在尝试使用"-".join(doc.xpath将所有内容绑定在一起解析出来,但输出会为下面显示的<document-id><classification-national>创建用连字符分隔的空格

<references-cited> <citation> 
<patcit num="00001"> <document-id>
<country>US</country> 
<doc-number>534632</doc-number> 
<kind>A</kind>
<name>Coleman</name> 
<date>18950200</date> 
</document-id> </patcit>
<category>cited by examiner</category>
<classification-national><country>US</country>
<main-classification>249127</main-classification></classification-national>
</citation>

注意并非每个<citation>内都存在所有儿童,有时他们根本不存在。

如何在尝试在<citation>下的多个条目的每个数据条目之间放置连字符时解析此xpath?

1 个答案:

答案 0 :(得分:1)

从这个XML(references.xml),

<references-cited> 
  <citation> 
    <patcit num="00001"> 
      <document-id>
        <country>US</country> 
        <doc-number>534632</doc-number> 
        <kind>A</kind>
        <name>Coleman</name> 
        <date>18950200</date> 
      </document-id> 
    </patcit>
    <category>cited by examiner</category>
    <classification-national>
      <country>US</country>
      <main-classification>249127</main-classification>
    </classification-national>
  </citation>

  <citation>
    <patcit num="00002">
      <document-id>
        <country>US</country>
        <doc-number>D28957</doc-number>
        <kind>S</kind>
        <name>Simon</name>
        <date>18980600</date>
      </document-id>
    </patcit>
    <category>cited by other</category>
  </citation>
</references-cited>

您可以获取<citation>的每个后代的文本内容,其内容如下:

from lxml import etree

doc = etree.parse("references.xml")
cits = doc.xpath('/references-cited/citation')

for c in cits:
    descs = c.xpath('.//*')
    for d in descs:
        if d.text and d.text.strip():
            print "%s: %s"  %(d.tag, d.text)
    print

输出:

country: US
doc-number: 534632
kind: A
name: Coleman
date: 18950200
category: cited by examiner
country: US
main-classification: 249127

country: US
doc-number: D28957
kind: S
name: Simon
date: 18980600
category: cited by other

此变体:

import sys
from lxml import etree

doc = etree.parse("references.xml")
cits = doc.xpath('/references-cited/citation')

for c in cits:
    descs = c.xpath('.//*')
    for d in descs:
        if d.text and d.text.strip():
            sys.stdout.write("-%s"  %(d.text))
    print

导致此输出:

-US-534632-A-Coleman-18950200-cited by examiner-US-249127
-US-D28957-S-Simon-18980600-cited by other