java使用xpath解析xml,java使用XPath解析xml
XML文件:widgets.xml
widText
public static void examineXmlFile(String path) throws Exception {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse(path);
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//node/@id");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
Node n = nodes.item(i);
System.out.println(nodes.item(i).getNodeValue());
}
}
另一个使用xPath的示例:ReadXMLbyXPath
package util.xml;
import java.io.File;
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.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.sun.org.apache.xpath.internal.NodeSet;
public class ReadXMLbyXPath {
public static void main(String[] arg ) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException
{
// parse the XML as a W3C Document
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = builder.parse(new File("E:/workspace/Java-Util/src/util/xml/widgets.xml"));
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/widgets/widget";
Node widgetNode = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
System.out.println(widgetNode.getNodeName());//节点名称
System.out.println(widgetNode.getNodeValue());//节点值是null,为什么?
System.out.println(widgetNode.getTextContent());//节点text
}
}