XML教程

根据xml节点,获取节点值路径

本文主要是介绍根据xml节点,获取节点值路径,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
from lxml import etree

s = '''
<Departments orgID="123" name="xmllist">
    <One>
        <orgID>124</orgID>
        <name>A</name>
        <type>type a</type>
        <status>Active</status>
            <Two>
                <orgID>125</orgID>
                <name>B</name>
                <type>type b</type>
                <status>Active</status>
                <Three>
                    <orgID>126</orgID>
                    <name>C</name>
                    <type>type c</type>
                    <status>Active</status>
                </Three>
            </Two>
    </One>
    <Department>
        <orgID>109449</orgID>
        <name>D</name>
        <type>type d</type>
        <status>Active</status>
    </Department>
</Departments>'''

root = etree.fromstring(s)
element = './/name'


def get_root_tag(element):
    all = []
    for target in root.xpath(element):
        parent_name = []
        result = []
        parent_name = find_parent_node(result, target)
        parent_name.insert(0, target.text)
        all.append(parent_name)
    return all


def find_parent_node(result, target):
    parent_node = target.find('..')
    if not hasattr(parent_node, 'tag'):
        return result
    else:
        result.append(parent_node.tag)
        return find_parent_node(result, parent_node)


name = get_root_tag(element)
for item in name:
    print('<'.join(item))

A<One<Departments
B<Two<One<Departments
C<Three<Two<One<Departments
D<Department<Departments

这篇关于根据xml节点,获取节点值路径的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!