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

我试图从给定XML文件中的特定元素中找到给定XML元素的相对深度,我尝试使用XPATH,但是我对XML解析不是很熟悉,也没有得到理想的结果.我还需要在计数时忽略数据元素.

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

父节点是:TS837_2000A_Loop< NM1_SubLoop_2< TS837_2010AA_Loop< NM1_BillingProviderName
因为NM109_BillingProviderIdentifier是NM1_BillingProviderName的子级,因此从TS837_2000A_Loop到NM1_BillingProviderName的相对深度为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::*)

这将使您计数到根.要获取相对计数,即从根以外的任何位置获取相对计数,假设名称不重叠,则可以执行以下操作:

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

根据是将电流还是基础元素包括在计数中,请使用“祖先或自身”或“祖先”轴.

PS:您可能应该感谢Pietro Saccardi如此慷慨地使您的帖子和庞大的XML(一行上有4kB ..)示例XML可读.

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念