【发布时间】:2011-12-07 01:26:01
【问题描述】:
我使用 python 和 lxml 来处理 xml。在我查询/过滤以到达我想要的节点后,但我遇到了一些问题。如何通过 xpath 获取其属性的值?这是我的输入示例。
>print(etree.tostring(node, pretty_print=True ))
<rdf:li xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" rdf:resource="urn:miriam:obo.chebi:CHEBI%3A37671"/>
我想要的值在 resource=... 中。目前我只是使用 lxml 来获取值。我想知道是否可以在纯 xpath 中进行?谢谢
编辑:忘了说,这不是根节点,所以我不能在这里使用 //。我在 xml 文件中有 2000-3000 个其他人。我的第一次尝试是使用“.@attrib”和“self::*@”,但这些似乎不起作用。
EDIT2:我会尽力解释(嗯,这是我第一次使用 xpath 处理 xml 问题。英语不是我最喜欢的领域之一......)。这是我的输入 sn-p http://pastebin.com/kZmVdbQQ (来自这里的完整一个 http://www.comp-sys-bio.org/yeastnet/ 使用版本 4)。
在我的代码中,我尝试使用资源链接 chebi(<rdf:li rdf:resource="urn:miriam:obo.chebi:...."/>).如果我从像 speciesTypes 这样的父节点开始,很容易在子节点中获取属性,但我想知道如果我从 rdf:li 开始怎么办。据我了解,xpath 中的“//”不仅会从任何地方寻找节点在当前节点中。
下面是我的代码
import lxml.etree as etree
tree = etree.parse("yeast_4.02.xml")
root = tree.getroot()
ns = {"sbml": "http://www.sbml.org/sbml/level2/version4",
"rdf":"http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"body":"http://www.w3.org/1999/xhtml",
"re": "http://exslt.org/regular-expressions"
}
#good enough for now
maybemeta = root.xpath("//sbml:speciesType[descendant::rdf:li[starts-with(@rdf:resource, 'urn:miriam:obo.chebi') and not(starts-with(@rdf:resource, 'urn:miriam:uniprot'))]]", namespaces = ns)
def extract_name_and_chebi(node):
name = node.attrib['name']
chebies = node.xpath("./sbml:annotation//rdf:li[starts-with(@rdf:resource, 'urn:miriam:obo.chebi') and not(starts-with(@rdf:resource, 'urn:miriam:uniprot'))]", namespaces=ns) #get all rdf:li node with chebi resource
assert len(chebies) == 1
#my current solution to get rdf:resource value from rdf:li node
rdfNS = "{" + ns.get('rdf') + "}"
chebi = chebies[0].attrib[rdfNS + 'resource']
#do protein later
return (name, chebi)
metaWithChebi = map(extract_name_and_chebi, maybemeta)
fo = open("metabolites.txt", "w")
for name, chebi in metaWithChebi:
fo.write("{0}\t{1}\n".format(name, chebi))
【问题讨论】:
-
用 xpath 解析 rdf xml 真的不是一个好主意。 XML 是树,而 RDF 是图,可以用不同的 rdfxml 表示同一个 rdf 图。您应该将 xml 视为一种交换格式,并使用 RDF 库从 XML 创建图形,然后直接使用图形。
-
感谢您的建议。但在这项工作中,我只想提取包含一些信息的节点,然后对其进行一些格式处理以在电子表格中使用。
标签: python xpath attributes sbml