我有一个关于如何通过按属性过滤外部元素来计算其他元素中的元素的问题。我有以下XML文档:
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<DSCT2C>
<TESTSTEPS APPLICATION="UGS">
<TESTSTEP ORDER_NUMBER="0">
<EN>Common Test</EN>
<DE>Allgemeiner Test</DE>
<TEST NEED_FUNCTION="true" FUNCTION_NAME="functionName">
<DESCRIPTION>
<DE>Hallo</DE>
<EN>Hello</EN>
</DESCRIPTION>
<FILES>
<FILE>test.prt</FILE>
<FILE>test.drw</FILE>
</FILES>
</TEST>
<TEST NEED_FUNCTION="false">
<DESCRIPTION>
<DE>Hallo2</DE>
<EN>Hello2</EN>
</DESCRIPTION>
<FILES>
</FILES>
</TEST>
</TESTSTEP>
<TESTSTEP ORDER_NUMBER="1">
<EN>Just a test</EN>
<DE>Nur ein Test</DE>
<TEST NEED_FUNCTION="true" FUNCTION_NAME="functionName123">
<DESCRIPTION>
<DE>Hallo</DE>
<EN>Hello</EN>
</DESCRIPTION>
<FILES>
<FILE>test.prt</FILE>
<FILE>test.drw</FILE>
</FILES>
</TEST>
<TEST NEED_FUNCTION="true" FUNCTION_NAME="functionName456">
<DESCRIPTION>
<DE>Hallo2</DE>
<EN>Hello2</EN>
</DESCRIPTION>
<FILES>
</FILES>
</TEST>
</TESTSTEP>
</TESTSTEPS>
</DSCT2C>
我想计算TEST
元素中的所有TESTSTEP
元素,例如ORDER_NUMBER=0
。我怎么能用DOM做到这一点?
答案 0 :(得分:0)
使用xpath表达式:
"//TESTSTEP[@ORDER_NUMBER = '0']/TEST"
然后获得返回的NodeList
的长度。
代码看起来像:
XPath xpath = XPathFactory.newInstance().newXPath()
NodeList tests = (NodeList)xpath.evaluate("//TESTSTEP[@ORDER_NUMBER = '0']/TEST", document, XPathConstants.NODESET);
int testCount = tests.getLength();
答案 1 :(得分:0)
试试这个
int n = 0;
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("1.xml"));
NodeList list = doc.getElementsByTagName("TESTSTEP");
for (int i = 0; i < list.getLength(); i++) {
Element e = (Element) list.item(i);
if (e.getAttribute("ORDER_NUMBER").equals("0")) {
n += e.getElementsByTagName("TEST").getLength();
}
}