简体   繁体   中英

Retrieve multiple attributes with XPath

I have an XML file that's similar to this (each element has more attributes):

    <DocBuild>
    <XMLDependency name="Name1" product="Product ABC" area="JKL" />
    <XMLDependency name="Name2" product="Product DEF" area="MNO" />
    <XMLDependency name="Name3" product="Product GHI" area="PQR" />
    </DocBuild>

I want to retrieve each 'name' attribute and the 'area' for that element so I can build a list that looks like this (I've inserted a dash between 'name' and 'area' for clarity):

    Name1-JKL
    Name2-MNO
    Name3-PQR

    public static Element getConfig(...) throws XPathExpressionException{
         String path = MessageFormat.format("//DocBuild//XMLDependency[@name='Name1']//@area ")
    }

Use some rules like regular expressions! In this case you must use "|" which is used as OR clause.

            // Create XPathFactory object
            XPathFactory xpathFactory = XPathFactory.newInstance();

            // Create XPath object
            XPath xpath = xpathFactory.newXPath();

            String name = null;
            try {
                XPathExpression expr =
                        xpath.compile("/DocBuild/XMLDependency[@name='Name1']//@name|/DocBuild/XMLDependency[@name='Name1']//@area");
                NodeList nl = (NodeList)expr.evaluate(doc,XPathConstants.NODESET);
                String nameAttr = "";
                for (int index = nl.getLength()-1; index >= 0; index--) {
                    Node node = nl.item(index);
                    nameAttr += node.getTextContent();
                    nameAttr += "-";
                }
                nameAttr = nameAttr.substring(0,nameAttr.lastIndexOf("-"));
                System.out.println(nameAttr);
                
            } catch (XPathExpressionException e) {
                e.printStackTrace();
            }

See XPath Syntax

This XPath 2.0 expression,

/DocBuild/XMLDependency/concat(@name,'-',@area)

evaluates directly to

Name1-JKL
Name2-MNO
Name3-PQR

for your sample XML, as requested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM