【发布时间】:2015-09-26 15:38:03
【问题描述】:
我试图从给定 XML 文件中的特定元素中找到给定 XML 元素的相对深度,我尝试使用 XPATH,但我对 XML 解析不是很熟悉,也没有得到想要的结果。我还需要在计数时忽略数据元素。
以下是我编写的代码和示例 XML 文件。
例如。 NM109_BillingProviderIdentifier 与 TS837_2000A_Loop 元素的深度为 4。
父节点为:TS837_2000A_Loop < NM1_SubLoop_2 < TS837_2010AA_Loop < NM1_BillingProviderName
因为NM109_BillingProviderIdentifier 是NM1_BillingProviderName 的子级,因此NM1_BillingProviderName 与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>
【问题讨论】:
-
4412 个字符的单行 XML?超过 4kB?请花点时间 (1) 将您的示例 XML 最小化为理解您的问题所需的内容,以及 (2) 对您的示例进行布局,使其易于阅读。请花一分钟阅读minimal reproducible example。另外,请说明“相对位置”。人物定位?节点位置?深度?