1.创建解析工厂
2.创建解析器
3.读xml文件,生成w3c.docment对象树
4.创建XPath对象
5.通过路径查找对象
例子:
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.XPathFactory;
import org.w3c.dom.Document;
public class MyXPathTest {
/**
* @param args
*/
public static void main(String[] args) {
try {
//创建解析工厂
DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance();
//创建解析器
DocumentBuilder builder=documentBuilderFactory.newDocumentBuilder();
//通过解析器读取文件,生成w3c.dom.Document象树
Document document=builder.parse("conf/55.xml");
//创建XPath对象
XPath xPath=XPathFactory.newInstance().newXPath();
//
//
//
//
//
//
//
//
//
//
//读取Model中属性id的值
String idPath="/Model/@id";
String id=(String) xPath.evaluate(idPath, document, XPathConstants.STRING);
System.out.println(“id=”+id);
//
//
//
//
//
//
//
//
//
//
String idNodePath="/Model/node[@nodetype=‘DynamicMoleNode’]/@id";
String idNode=(String) xPath.evaluate(idNodePath, document, XPathConstants.STRING);
System.out.println(“idNode=”+idNode);
//
//
//
//
//
//
// <node id=" nodetype=“DynamicMoleNode”>
//
//
//
//
//
String rtfPath="/Model/node[@nodetype=‘DynamicMoleNode’]/node[@nodetype=‘Text’]/@rtf";
String rtf=(String) xPath.evaluate(rtfPath, document, XPathConstants.STRING);
System.out.println(“rtf=”+rtf);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
同一xpath路径下有多个Element对象
String path="/XTextDocument/XElements/Element[@type=‘XTextBody’]/XElements/Element";
NodeList nodeList=(NodeList) xPath.evaluate(path,document, XPathConstants.NODESET);
System.out.println(“nodeList====”+nodeList.getLength());
原文:https://www.cnblogs.com/fmain/archive/2019/06/14/11024064.html

903

被折叠的 条评论
为什么被折叠?



