import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
public class XMLXpathReadder {
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new FileInputStream(new File("C:\\Test.xml")));// same xml comments as above.
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
Element userElement = (Element) xpath.evaluate("/schema/element", document,
XPathConstants.NODE);
System.out.println(userElement.getAttribute("id"));
System.out.println(userElement.getAttribute("name"));
}
}
上面的代码对我有用。
但是如何读取所有元素的值。我总是只得到第一个元素节点。
<?xml version="1.0" encoding="UTF-8"?>
<schema>
<element name="name_ele1" id="_1" >test name1</element>
<element name="name_ele2" id="_2" >test name2</element>
<element name="name_ele2" id="_3" >test name3</element>
</schema>