java使用XPath解析xml

m4ed 9年前發布 | 2K 次閱讀 Java

XML文件:widgets.xml

<widgets>
<widget value="widgetValue">widText</widget>
</widgets>

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());
    }
}</pre> 


另一個使用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

}

}</pre>

 本文由用戶 m4ed 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!