Have you ever treated XML only using library provided in Java SDK?
I think many people use external library for treating XML in Java.
To be honest, I would prefer to use JDom ;P
But I think it's good thing to know how to treat XML only using Java SDK.
I will show you small code snippet for treating XML especially from XPath usage.
The classes you should remember for treating XML is:
- DocumentBuilderFactory
- DocumentBuilder
- Document
- XPathFactory
- XPath
- XPathExpression
- XPathConstants
- NodeList
- Node
Oops, a bit quite too much.
Anyway I will show you an example code for reading XML string and select nodes by XPath.
package com.dulesoftware.xpath;
import java.io.IOException;
import java.io.StringReader;
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.XPathExpression;
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.InputSource;
import org.xml.sax.SAXException;
public class XPathExample {
public static void main(String[] args) throws XPathExpressionException, SAXException, IOException, ParserConfigurationException {
String xmlString =
"<root>"
+ "<items id=\"12345\">"
+ " <item>"
+ " <name>Java</name>"
+ " </item>"
+ " <item>"
+ " <name>C#</name>"
+ " </item>"
+ "</items>"
+ "</root>";
// build Document
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xmlString)));
// prepare xpath
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xPath = xPathfactory.newXPath();
// xpaths
XPathExpression itemPathExpr = xPath.compile("/root/items/item");
XPathExpression itemsIdPathExpr = xPath.compile("/root/items/@id");
XPathExpression itemNamePathExpr = xPath.compile("name"); // you should not put "/" if you evaluate xpath on child node
// get attribute
String id = (String)itemsIdPathExpr.evaluate(doc, XPathConstants.STRING);
System.out.println("id="+id);
// get nodeset
NodeList items = (NodeList)itemPathExpr.evaluate(doc, XPathConstants.NODESET);
for(int i = 0, len = items.getLength(); i < len; i++)
{
Node item = items.item(i);
System.out.println("node name="+item.getNodeName());
// get node
Node name = (Node)itemNamePathExpr.evaluate(item, XPathConstants.NODE);
System.out.println("child node value=" + name.getTextContent());
}
}
}
I think code itself is really straight forward and not so bad.
But the disadvantages of the XML library provided by Java SDK which I felt after I wrote this post is:
- Too much casting
- can't use foreach to iterate NodeList
- Always need Factory and newDocument or newXPath - don't you think quite annoying?
コメント