Tue Apr 23, 2013 10:52 pm
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
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.xml.sax.SAXException;
public class XPathUtility {
private XPathUtility() {
}
public static String evaluateNode(String expression, InputStream xmlFile) {
Object[] params = { expression, xmlFile };
Node result = null;
DocumentBuilder parser = null;
try {
parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (ParserConfigurationException parserConfigurationException) {
// Do Something
}
Document doc = null;
try {
doc = parser.parse(xmlFile);
} catch (SAXException saxException) {
// Do Something
} catch (IOException ioException) {
// Do Something
}
XPath xpath = XPathFactory.newInstance().newXPath();
try {
result = (Node) xpath.evaluate(expression, doc, XPathConstants.NODE);
} catch (XPathExpressionException xPathExpressionException) {
// Do Something
}
Document parsedDoc = null;
OutputStream os = null;
try {
parsedDoc = parser.newDocument();
Node importedNode = parsedDoc.importNode(result, true);
os = new ByteArrayOutputStream();
// Prepare the DOM document for writing
Source source = new DOMSource(importedNode);
// Prepare the output String
Result outpuResult = new StreamResult(os);
// Write the DOM document to the outputStream
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
xformer.transform(source, outpuResult);
} catch (TransformerFactoryConfigurationError e) {
// Do Something
} catch (TransformerException e) {
// Do Something
}
return os.toString();
}
}
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com
Powered by phpBB © phpBB Group.