我使用Python和lxml来处理XML。在查询/筛选以获取我想要的节点后,我遇到了一些问题。如何通过xpath获取其属性值?这是我的输入示例。
我想要的值在resource=...中。目前我只是使用lxml来获取该值。我想知道是否有可能仅使用纯xpath来实现?谢谢。
编辑:忘了说,这不是根节点,所以我不能在这里使用//。我的xml文件中有大约2000-3000个其他节点。我的第一次尝试是尝试使用".@attrib"和"self::*@",但这些似乎不起作用。
编辑2:我会尽力解释(好吧,这是我第一次使用xpath解决xml问题,并且英语不是我最喜欢的领域...)。这是我的输入片段http://pastebin.com/kZmVdbQQ(从这里http://www.comp-sys-bio.org/yeastnet/使用版本4获取完整信息)。
在我的代码中,我尝试使用资源链接chebi(
以下是我的代码:
>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::*@",但这些似乎不起作用。
编辑2:我会尽力解释(好吧,这是我第一次使用xpath解决xml问题,并且英语不是我最喜欢的领域...)。这是我的输入片段http://pastebin.com/kZmVdbQQ(从这里http://www.comp-sys-bio.org/yeastnet/使用版本4获取完整信息)。
在我的代码中,我尝试使用资源链接chebi(
<rdf:li rdf:resource="urn:miriam:obo.chebi:...."/>)
获取speciesTypes节点。然后,我尝试从rdf:li的rdf:resource属性中获取值。问题是,我相当确定如果我从父节点(如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))