2009年1月3日

XML Parsing With DOM and XPath

Document Object Model (DOM)
W3C XML Path Language (XPath)

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;


public class Main {

public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();

StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
.append("<root name=\"attr\">")
.append("<name>TEST XML</name>")
.append("<user>")
.append("<name>Solnone</name>")
.append("</user>")
.append("</root>");
byte[] buf = sb.toString().getBytes("UTF-8");
InputStream is = new ByteArrayInputStream(buf);
Document doc = null;
try {
doc = builder.parse(is);

} finally {
is.close();
}
System.out.println("Encoding: " + doc.getXmlEncoding());
System.out.println("Root tag Name: " + doc.getDocumentElement().getTagName());
XPathFactory xpathFactory = javax.xml.xpath.XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
System.out.println("Xpath: //text()");
XPathExpression expr = xpath.compile("//text()");
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(" " + nodes.item(i).getNodeValue());
}
}

}

/*
Encoding: UTF-8
Root tag Name: root
Xpath: //text()
TEST XML
Solnone
*/

沒有留言:

網誌存檔