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

时间:2015-09-26 15:38:03

标签: java xml xpath

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

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

父节点是:TS837_2000A_Loop < NM1_SubLoop_2 < TS837_2010AA_Loop < NM1_BillingProviderName 由于NM109_BillingProviderIdentifierNM1_BillingProviderName的孩子,因此来自NM1_BillingProviderName的{​​{1}}的相对深度为4(包括TS837_2000A_Loop)。

TS837_2000A_Loop

&#13;
&#13;
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);

    }
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

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

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

这将为您提供根数量。要获取相对计数,即从根以外的任何其他位置开始,假设名称不重叠,您可以这样做:

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

根据计数中是否应包含当前或基本元素,使用ancestor-or-selfancestor轴。

PS:您应该感谢Pietro Saccardi如此友好地发布您的帖子以及您的大量(4kB一行......)样本XML可读。

相关问题