0

我有一个关于如何通过按属性过滤外部元素来计算其他元素中的元素的问题。我有以下 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 做到这一点?

4

2 回答 2

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();
于 2013-05-22T13:29:38.350 回答
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();
        }
    }
于 2013-05-22T13:37:24.490 回答