자바 xpath 분석 xml 예제 공유 사용
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
<?xml version="1.0" encoding="utf-8" ?>
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
실행 효과
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.