如何使用 XPATH 获取 XML 元素的相对深度

2024-02-04

我试图从给定 XML 文件中的特定元素查找给定 XML 元素的相对深度,我尝试使用 XPATH,但我对 XML 解析不太熟悉,并且没有得到所需的结果。我还需要在计数时忽略数据元素。

下面是我编写的代码和示例 XML 文件。 例如。的深度NM109_BillingProviderIdentifier from TS837_2000A_Loop元素为4。

父节点是:TS837_2000A_Loop < NM1_SubLoop_2 < TS837_2010AA_Loop < NM1_BillingProviderName as NM109_BillingProviderIdentifier是一个孩子NM1_BillingProviderName因此相对深度NM1_BillingProviderName from TS837_2000A_Loop为 4(包括TS837_2000A_Loop).

package com.xmlexamples;
import java.io.File;
import java.io.FileInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;


public class XmlParser {

public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(false);
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new FileInputStream(new File("D://sample.xml")));

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        String expression;      
        expression = "count(NM109_BillingProviderIdentifier/preceding-sibling::TS837_2000A_Loop)+1";                
        Double d = (Double) xpath.compile(expression).evaluate(doc, XPathConstants.NUMBER);     
        System.out.println("position from  TS837_2000A_Loop " + d);

    }
}
<?xml version='1.0' encoding='UTF-8'?>
<X12_00501_837_P xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <TS837_2000A_Loop>
        <NM1_SubLoop_2>
            <TS837_2010AA_Loop>
                <NM1_BillingProviderName>
                    <NM103_BillingProviderLastorOrganizationalName>VNA of Cape Cod</NM103_BillingProviderLastorOrganizationalName>
                    <NM109_BillingProviderIdentifier>1487651915</NM109_BillingProviderIdentifier>
                </NM1_BillingProviderName>
                <N3_BillingProviderAddress>
                  <N301_BillingProviderAddressLine>8669 NORTHWEST 36TH ST </N301_BillingProviderAddressLine>
                </N3_BillingProviderAddress>
            </TS837_2010AA_Loop>
        </NM1_SubLoop_2>
    </TS837_2000A_Loop>
</X12_00501_837_P>     

获取任何节点深度的关键方法是计算其祖先(包括父节点、父节点的父节点等):

count(NM109_BillingProviderIdentifier/ancestor-or-self::*)

这将为您提供一直到根的计数。为了得到relative计数,即从根以外的任何位置,假设名称不重叠,您可以这样做:

count(NM109_BillingProviderIdentifier/ancestor-or-self::*)
- count(NM109_BillingProviderIdentifier/ancestor::TS837_2000A_Loop/ancestor::*)

根据当前元素或基本元素是否应包含在计数中,使用ancestor-or-self or ancestor axis.


PS:你可能应该感谢彼得罗·萨卡尔迪 https://stackoverflow.com/users/1749822/pietro-saccardi非常感谢您的帖子和巨大的(一行 4kB..)示例 XML 可读。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 XPATH 获取 XML 元素的相对深度 的相关文章

随机推荐