2020年11月4日 星期三

XML XPathExpression

https://stackoverflow.com/questions/15421847/retrieving-attributes-and-values-of-child-nodes-of-an-xml-element-in-java

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;


    final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));

    final XPath xPath = XPathFactory.newInstance().newXPath();

    final XPathExpression expression = xPath.compile("//course[@name='AdvancedAlgorithm']//Teacher");


    final NodeList nodeList = (NodeList) expression.evaluate(doc, XPathConstants.NODESET);


    for (int i = 0; i < nodeList.getLength(); ++i) {

        System.out.println(((Element)nodeList.item(i)).getAttribute("name"));

    }


沒有留言:

張貼留言