具有不同名称的所有子节点的 XPATH

XPATH for all child nodes with different names

我有一个包含各种子元素的父元素,我需要对其进行计数。我遇到的问题是每个子元素都是不同的名称,所以每次我使用 count(*) 时,编号都会重新开始。我需要编号为 1.1、1.2、1.3...

父标签为 <application> 为 1,<ident> 为 1.1,<kitapplic> 为 1.2,<tctoproof> 为 1.3

我以为我可以做一个 count(child::application) 但那没有用。感谢您的帮助。

<application>
    <ident>
        <para>This Technical Order is applicable.</para>
    </ident>
    <kitapplic>
        <kitapptbl>
            <kitapptblrow>
                <model>Model</model>
                <serialno>Serial Number</serialno>
                <kitno>Kit Required</kitno>
            </kitapptblrow>
        </kitapptbl>
    </kitapplic>
    <tctoproof>
        <para>Time Compliance Technical Order (TCTO) verification, in accordance
            with TO 00-5-15, was accomplished 28 August 2019 at Nellis Air Force
        Base with GCS serial number 5147.</para>
    </tctoproof>
</application>

使用 XPath,您可以使用 count preceding-siblingconcat 来获得所需的数字。 kitapplic 示例:

concat("1.",count(application/kitapplic/preceding-sibling::*)+1)

输出:1.2

如果您需要一个包含 1.1、1.2、1.3 的列表,您可以为应用程序元素的每个子元素执行操作(Python 中的示例):

data = """<application>
    <ident>
        <para>This Technical Order is applicable.</para>
    </ident>
    <kitapplic>
        <kitapptbl>
            <kitapptblrow>
                <model>Model</model>
                <serialno>Serial Number</serialno>
                <kitno>Kit Required</kitno>
            </kitapptblrow>
        </kitapptbl>
    </kitapplic>
    <tctoproof>
        <para>Time Compliance Technical Order (TCTO) verification, in accordance
            with TO 00-5-15, was accomplished 28 August 2019 at Nellis Air Force
        Base with GCS serial number 5147.</para>
    </tctoproof>
</application>"""

import lxml.html
tree = lxml.html.fromstring(data)

for el in tree.xpath("//application/*"):
    print(el.xpath("concat(name(.),' 1.',count(./preceding-sibling::*)+1)"))

输出:

ident 1.1
kitapplic 1.2
tctoproof 1.3