Here is my xml file: bookstore.xml and what I am trying to do is I provide xpath as input and it should give me that node value of it. but it gives me null values.
<?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">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
here is the java code :
public class XmlParserUsingXpath {
public void xmlParser(XPathExpression xpathexp) throws ParserConfigurationException, XPathExpressionException{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder dbuilder = factory.newDocumentBuilder();
Document doc=null;
try {
doc= dbuilder.parse(new FileInputStream("D:\\Bookstore.xml"));
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
doc.getDocumentElement().normalize();
Object result = xpathexp.evaluate( doc, XPathConstants.NODESET );
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i));
}
public static void main(String[] args){
XmlParserUsingXpath o1= new XmlParserUsingXpath();
XPath x=XPathFactory.newInstance().newXPath();
System.out.println("Enter the Xpath Expression : ");
Scanner sc= new Scanner(System.in);
String scan= sc.nextLine();
try {
o1.xmlParser(x.compile(scan));
} catch (XPathExpressionException | ParserConfigurationException e) {
e.printStackTrace();
}
}
}
now when i provide " //book
" as input, it gives me
[book: null]
[book: null]
[book: null]
[book: null]
or "/bookstore/book[3]/author
" would give
[author: null]
[author: null]
[author: null]
[author: null]
[author: null]
我只对角地阅读了您的文章,但尝试:
factory.setNamespaceAware(false);
Change:
Object result = xpathexp.evaluate( doc, XPathConstants.NODESET );
TO
Object result = xpathexp.evaluate( doc, XPathConstants.NODE );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.