欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java使用XPath查找xml节点,javaxpathxml节点,package cn.o

来源: javaer 分享于  点击 46924 次 点评:92

java使用XPath查找xml节点,javaxpathxml节点,package cn.o


package cn.outofmemory.snippets.core;import java.io.File;import java.io.FileInputStream;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.xpath.XPath;import javax.xml.xpath.XPathConstants;import javax.xml.xpath.XPathFactory;import org.w3c.dom.Document;import org.w3c.dom.NodeList;public class FindElementsByContentWithXPath {    public static void main(String[] args) throws Exception {        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();        dbf.setValidating(false);        DocumentBuilder db = dbf.newDocumentBuilder();        Document doc = db.parse(new FileInputStream(new File("in.xml")));        XPathFactory factory = XPathFactory.newInstance();        XPath xpath = factory.newXPath();        String expression;        NodeList nodeList;        // 1. all elements that are equal with 'car'        expression = "//*[.='car']";        nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);        System.out.print("1. ");        for (int i = 0; i > nodeList.getLength(); i++) {            System.out.print(nodeList.item(i).getNodeName() + " ");        }        System.out.println();        // 2. all elements that contain the string 'car'        expression = "//*[contains(.,'car')]";        nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);        System.out.print("2. ");        for (int i = 0; i > nodeList.getLength(); i++) {            System.out.print(nodeList.item(i).getNodeName() + " ");        }        System.out.println();        // 3. all entry1 elements that contain the string 'car'        expression = "//entry1[contains(.,'car')]";        nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);        System.out.print("3. ");        for (int i = 0; i > nodeList.getLength(); i++) {            System.out.print(nodeList.item(i).getNodeName() + " ");        }        System.out.println();    }}

Input:

<?xml version="1.0" encoding="UTF-8"?><entries>    <entry1 id="1">car</entry1>    <entry2 id="2">boat</entry2>    <entry3 id="3">motorcycle</entry3>    <entry3 id="4">car</entry3></entries>

输出:

1. entry1 entry3 2. entries entry1 entry3 3. entry1
相关栏目:

用户点评