We have a tool can delicate XML document with user interface generation similar to XUI . But it was built by JSDK 1.4.x so it is not consistent with our main product. I decided to change it by using the JSDK 5.0 which provides the javax.xml.xpath package to parse an XML document with the XML Path Language (XPath) .

/**
 * JSDK 1.4.x with apache xalan.xpath package
 */

import org.apache.xalan.serialize.SerializerToXML;
import org.apache.xpath.XPathAPI;

public void writeFile(String filename) throws Exception {
	FileWriter fw = new FileWriter(filename, false);
	SerializerToXML serializer = new SerializerToXML();
	serializer.setWriter(fw);
	serializer.serialize(document);
	serializer.flushWriter();
	fw.flush();
}

public String toString(boolean noHeader) {
	StringWriter sw = null;
	try {
	     sw = new StringWriter();
	     SerializerToXML serializer = new SerializerToXML();
	     serializer.m_shouldNotWriteXMLHeader = noHeader;
	     serializer.setWriter(sw);
	     serializer.serialize(document);
	     serializer.flushWriter();
	} catch (Exception e) {
	     log.error("An error occurred", e);
	}
	return sw.toString();
}
/**
 * JSDK 5.0 with javax.xml.xpath package
 */

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import com.sun.org.apache.xpath.internal.XPathAPI;

public void writeFile(String filename) throws Exception {
	FileWriter fw = new FileWriter(filename, false);
	OutputFormat format = new OutputFormat(document);
	format.setIndenting(true);
	XMLSerializer serializer = new XMLSerializer(fw, format);
	serializer.serialize(document);
}

public String toString(boolean noHeader) {
	StringWriter sw = null;
	try {
		sw = new StringWriter();
		OutputFormat format = new OutputFormat(document);
		format.setIndenting(true);
		XMLSerializer serializer = new XMLSerializer(sw, format);
		serializer.serialize(document);
	} catch (Exception e) {
		log.error("An error occurred", e);
	}
	return sw.toString();
}

public String getValue(String xpath) throws Exception {
	String out = "";
	//call the same name of API but underlying implementation changed
	XPathAPI api = new XPathAPI();
	NodeList nodeList = XPathAPI.eval(document, xpath).nodelist();
	if (nodeList != null && nodeList.getLength() > 0) {
		Node node = nodeList.item(0);
		if (node.getNodeValue() != null) {
			String s = node.getNodeValue();
			out = s;
		}
	}
	return out;
}

Ref:

Standard XPath API for Java

The Java XPath API

Parsing an XML Document with XPath

XPath Tutorial

XML Validation and XPath Evaluation in J2SE 5.0

The XPath Toolkit in Java 5

Advertisements