【问题标题】:Get XPATH of certain element in python (without using 'lxml')获取python中某些元素的XPATH(不使用'lxml')
【发布时间】:2017-11-07 06:36:34
【问题描述】:

我有一个 XML (Output.xml):

<condition>
    <comparison compare="and">
        <comparison compare="contains">
            <operand  type="string"/>
            <operand type="string" value="Agent"/>
        </comparison>
        <comparison compare="gt">
            <operand type="float"/>
            <operand type="int" />
        </comparison>
    </comparison>
</condition>

完美运行的python代码:

from lxml import etree

tree = etree.parse('Output.xml')

for condition in tree.xpath('//operand'):   
    print tree.getelementpath(condition)

结果:

/condition/comparison/comparison[1]/operand[1]
/condition/comparison/comparison[1]/operand[2]
/condition/comparison/comparison[2]/operand[1]
/condition/comparison/comparison[2]/operand[2]

我正在使用不支持“LXML”模块的 Apache NiFi(使用 Jython)。有什么方法可以使用不同的模块(如 xml.etree.ElementTree)获得相同的输出,我可以从提供的 xml 中提取某些元素的 xpath?

【问题讨论】:

    标签: python lxml elementtree apache-nifi


    【解决方案1】:

    您可以使用xml.etree.ElementTree

    import xml.etree.ElementTree
    e = xml.etree.ElementTree.parse('output.xml').getroot()
    
    root = e.tag
    print(root)
    for c in e.findall('.//'):
        print(c.tag)
    

    只是向您展示如何继续,(这会为您提供 xml 中的所有标签)

    condition
    comparison
    comparison
    operand
    operand
    comparison
    operand
    operand
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多