首页 文章

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

提问于
浏览
2

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

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

父节点是: TS837_2000A_Loop < NM1_SubLoop_2 < TS837_2010AA_Loop < NM1_BillingProviderName ,因为 NM109_BillingProviderIdentifierNM1_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>

1 回答

  • 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可读 .

相关问题