中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

java使用XPath解析xml

2018-07-20    來源:open-open

容器云強(qiáng)勢(shì)上線!快速搭建集群,上萬Linux鏡像隨意使用

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

另一個(gè)使用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());//節(jié)點(diǎn)名稱
     System.out.println(widgetNode.getNodeValue());//節(jié)點(diǎn)值是null,為什么?
     System.out.println(widgetNode.getTextContent());//節(jié)點(diǎn)text

  }

}

標(biāo)簽:

版權(quán)申明:本站文章部分自網(wǎng)絡(luò),如有侵權(quán),請(qǐng)聯(lián)系:west999com@outlook.com
特別注意:本站所有轉(zhuǎn)載文章言論不代表本站觀點(diǎn)!
本站所提供的圖片等素材,版權(quán)歸原作者所有,如需使用,請(qǐng)與原作者聯(lián)系。

上一篇:Java 判斷兩個(gè)日期相差多少天

下一篇:java實(shí)現(xiàn)截屏程序