It's..... COMPLICATED!
ps.txt contains the entire fault.... you can adapt to read from a String...
package com.integration.xpath;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
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.SAXException;
public class XPathRunner {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
doFault();
}
private static void doFault() throws ParserConfigurationException,
SAXException, IOException, XPathExpressionException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = factory.newDocumentBuilder();
File f = new File("st.txt");
Document doc = builder.parse(f);
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
xpath.setNamespaceContext(new PersonalNamespaceContext());
XPathExpression expr = xpath.compile("//bea_fault:stacktrace/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
Node item = nodes.item(i);
System.out.println(item.getNodeValue());
}
}
public static class PersonalNamespaceContext implements NamespaceContext {
public String getNamespaceURI(String prefix) {
if (prefix == null) throw new NullPointerException("Null prefix");
else if ("env".equals(prefix)) return "http://schemas.xmlsoap.org/soap/envelope/";
else if ("bea_fault".equals(prefix)) return "http://www.bea.com/servers/wls70/webservice/fault/1.0.0";
else if ("xml".equals(prefix)) return XMLConstants.XML_NS_URI;
return XMLConstants.NULL_NS_URI;
}
// This method isn't necessary for XPath processing.
public String getPrefix(String uri) {
throw new UnsupportedOperationException();
}
// This method isn't necessary for XPath processing either.
public Iterator getPrefixes(String uri) {
throw new UnsupportedOperationException();
}
}
}
thank you to http://www.ibm.com/developerworks/library/x-javaxpathapi.html
Sunday, May 2, 2010
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment