java如何使用xpath解析xml

这篇文章给大家分享的是有关java如何使用xpath解析xml的内容。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。

邯郸ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:18980820575(备注:SSL证书合作)期待与您的合作!

XPath即为XML路径语言(XML Path Language),它是一种用来确定XML文档中某部分位置的语言。XPath基于XML的树状结构,提供在数据结构树中找寻节点的能力。起初 XPath 的提出的初衷是将其作为一个通用的、介于XPointer与XSL间的语法模型。但是 XPath 很快的被开发者采用来当作小型查询语言
XPathTest.java

package com.hongyuan.test;
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.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XPathTest {
 public static void main(String[] args) throws ParserConfigurationException,
   SAXException, IOException, XPathExpressionException {
  // 解析文件,生成document对象
  DocumentBuilder builder = DocumentBuilderFactory.newInstance()
    .newDocumentBuilder();
  Document document = builder.parse(new File("bookstore.xml"));
  // 生成XPath对象
  XPath xpath = XPathFactory.newInstance().newXPath();
  // 获取节点值
  String webTitle = (String) xpath.evaluate(
    "/bookstore/book[@category='WEB']/title/text()", document,
    XPathConstants.STRING);
  System.out.println(webTitle);
  System.out.println("===========================================================");
  // 获取节点属性值
  String webTitleLang = (String) xpath.evaluate(
    "/bookstore/book[@category='WEB']/title/@lang", document,
    XPathConstants.STRING);
  System.out.println(webTitleLang);
  System.out.println("===========================================================");
  // 获取节点对象
  Node bookWeb = (Node) xpath.evaluate(
    "/bookstore/book[@category='WEB']", document,
    XPathConstants.NODE);
  System.out.println(bookWeb.getNodeName());
  System.out.println("===========================================================");
  // 获取节点集合
  NodeList books = (NodeList) xpath.evaluate("/bookstore/book", document,
    XPathConstants.NODESET);
  for (int i = 0; i < books.getLength(); i++) {
   Node book = books.item(i);
   System.out.println(xpath.evaluate("@category", book,
     XPathConstants.STRING));
  }
  System.out.println("===========================================================");
 }
}

bookstore.xml



 
   Everyday Italian 
   Giada De Laurentiis 
   2005 
   30.00 
 
 
   Harry Potter 
   J K. Rowling 
   2005 
   29.99 
 
 
   Learning XML 
   Erik T. Ray 
   2003 
   39.95 
 

感谢各位的阅读!关于java如何使用xpath解析xml就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到吧!


本文标题:java如何使用xpath解析xml
转载注明:http://pwwzsj.com/article/jssjoo.html