简体   繁体   English

XPATH-获取父级和子级的元组

[英]XPATH - get tuples of parent and child

Suppose this is my XML: 假设这是我的XML:

<animals>
   <mammals> 
      <an>dog</an>
      <an>cat</an>
   </mammals>
   <reptiles>
      <an>snake</an>
   </reptiles>
</animals>

What I want is to get tuples like that using xpath : 我想要的是使用xpath获得类似的元组:

(mammals,dog)
(mammals,cat)
(reptiles,snake)

To get each of them separately, or both of them with 2 queries is easy. 要分别获取它们,或者通过两个查询来获取它们都很容易。 I was wondering if there is a way to get it (or very similar output) in 1 xpath query. 我想知道是否有一种方法可以在1个xpath查询中获取它(或非常相似的输出)。

Any help will be appreciated! 任何帮助将不胜感激!

Use lxml : 使用lxml

from io import StringIO

from lxml import etree

xml = """<animals>
   <mammals> 
      <an>dog</an>
      <an>cat</an>
   </mammals>
   <reptiles>
      <an>snake</an>
   </reptiles>
</animals>"""

tree = etree.parse(StringIO(xml))

for x in tree.xpath("/animals/*"):
    for y in x:
        print((x.tag, y.text))

Output: 输出:

('mammals', 'dog')
('mammals', 'cat')
('reptiles', 'snake')

Try using xml module in python 尝试在python中使用xml模块

from xml.etree import  ElementTree

def parse_data(xml_str):
    output = []
    tree = ElementTree.fromstring(xml_str)
    for m in tree.getchildren():
        for n in m.getchildren():
           output.append((m.tag, n.text,))
    return output

xml_str = '''
<animals>
   <mammals> 
      <an>dog</an>
      <an>cat</an>
   </mammals>
   <reptiles>
      <an>snake</an>
   </reptiles>
</animals>'''

print parse_data(xml_str)
# output: [('mammals', 'dog'), ('mammals', 'cat'), ('reptiles', 'snake')]

In XPath 2.0 or above you can use for construct ( demo ) : 在XPath 2.0或以上,你可以使用for结构( 演示 ):

for $x in /animals/*/*
return concat($x/parent::*/name(), ',', $x/text())

But in lxml , which only supports XPath 1.0, we need to replace it with python's for loop : 但是在仅支持XPath 1.0的lxml ,我们需要将其替换为python的for循环:

from lxml import etree

raw = """<animals>
   <mammals> 
      <an>dog</an>
      <an>cat</an>
   </mammals>
   <reptiles>
      <an>snake</an>
   </reptiles>
</animals>"""
root = etree.fromstring(raw)

for x in root.xpath("/animals/*/*"):
    print (x.getparent().tag, x.text)

This xpath returns the requested string but only for the first element. 该xpath返回请求的字符串,但仅返回第一个元素。 Could be hard to do with pure XPath 使用纯XPath可能很难

'concat("(", local-name(//animals/*), ",", //animals/*/an/text(), ")")'

xmllint --xpath 'concat("(", local-name(//animals/*), ",", //animals/*/an/text(), ")")' ~/tmp/test.xml
(mammals,dog)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM