以下為XML檔:
<?xml version="1.0" encoding="UTF-8" ?>
<AAA>
<BBB>
<A>a1</A>
<B>b1</B>
<C>c1</C>
<D>d1</D>
</BBB>
<BBB>
<A>a2</A>
<B>b2</B>
<C>c2</C>
<D>d2</D>
</BBB>
</AAA>
以下為Java Code:
import javax.xml.xpath.*; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; public class TestXML { public static void main(String[] args) throws XPathExpressionException { XPath xpath = XPathFactory.newInstance().newXPath(); InputSource inputSource = new InputSource("D:/test.xml"); NodeList nodes = (NodeList) xpath.evaluate("/AAA/BBB", inputSource, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { String a = xpath.evaluate("A", nodes.item(i)); String b = xpath.evaluate("B", nodes.item(i)); String c = xpath.evaluate("C", nodes.item(i)); String d = xpath.evaluate("D", nodes.item(i)); System.out.println("a="+a+"b="+b+"c="+c+"d="+d); } } }
沒有留言:
張貼留言