java使用XPath解析xml详解编程语言

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("[email protected]"); 
 
        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 
 
  } 
 
}

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/10966.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论