使用python为非标准xm提供适当的xpath语法

2024-05-23 22:26:50 发布

您现在位置:Python中文网/ 问答频道 /正文

输入文件实际上是附加到一个文件的多个XML文件。(来源于Google Patents)。这是一个例子:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE us-patent-grant SYSTEM "us-patent-grant-v42-2006-08-23.dtd" [ ]>
<us-patent-grant lang="EN" dtd-version="v4.2 2006-08-23">
<applicants>
<applicant sequence="001" app-type="applicant-inventor" designation="us-only">
<addressbook><last-name>Beyer</last-name>
<first-name>Daniel Lee</first-name>
<address><city>Franklin</city>
<state>TN</state>
<country>US</country></address></addressbook>
<nationality><country>omitted</country></nationality>
<residence><country>US</country></residence>
</applicant>
<applicant sequence="002" app-type="applicant-inventor" designation="us-only">
<addressbook><last-name>Friedland</last-name>
<first-name>Jason Michael</first-name>
<address><city>Franklin</city>
<state>TN</state>
<country>US</country></address></addressbook>
<nationality><country>omitted</country></nationality>
<residence><country>US</country></residence>
</applicant>
</applicants>
</us-patent-grant>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE us-patent-grant SYSTEM "us-patent-grant-v42-2006-08-23.dtd" [ ]>

我正在尝试为<applicant>内的所有子代和孙代创建一个带有"-".joinxpath的字符串,使用python中的以下代码和lxml:

import urllib2, os, zipfile
from lxml import etree
count = 0
for item in xmlSplitter(zf.open(xml_file)):
  count += 1
  if count > 1: break
  doc = etree.XML(item)
  docID = "-".join(doc.xpath('//publication-reference/document-id/*/text()'))
  title = first(doc.xpath('//invention-title/text()'))
  applicant = "-".join(doc.xpath('//applicants/applicant/*/text()'))
  print "DocID:    {0}\nTitle:    {1}\nApplicant: {2}\n".format(docID,title,applicant)
  outFile.write(str(docID) +"|"+ str(title) +"|"+ str(applicant) +"\n")

我尝试过多行xpath combinations,但是我不能为<applicants>生成一个连字符的字符串,虽然//text()无法到达孙女,但它对串接没有帮助。选择<applicant>的子代和子代中的所有文本并将其打孔成字符串的合适xpath语法是什么?虽然在这个例子中没有显示,但是有没有一种方法可以忽略可能出现在文本行开头的unicode(我相信它出现在后面的一些xml文档中)?我希望得到的“申请人”输出应该类似于:

^{pr2}$

Tags: namecityaddressxmlcountryxpathfirstlast
1条回答
网友
1楼 · 发布于 2024-05-23 22:26:50

这个问题与this other question of yours非常相似。在

这里有两个问题:

  1. 如何从“非标准XML”到“标准XML”?在
  2. 如何使用XPath获取子元素的文本值并将它们连接起来?在

在攻击2之前,你需要先解1。如果你需要帮助,可以另问一个问题。在

“非标准XML”与“根本不是XML”相同。不能将其解析为XML,也不能对其使用XPath。但你用了一种让人觉得你无论如何都在试图这么做。在

假设您的问题实际上是关于使用“标准XML”,那么使用my answer to your other question中相同的方法如何?在

相关问题 更多 >