| Author |
java Xpath Namespace problem Resolved
|
Raju Nagaraj
Greenhorn
Joined: Apr 03, 2009
Posts: 5
|
|
Hi,
Earlier i posted a topic by the subject line Xpath Namespace problem in this forum for a soution to the xpath namespace problem.
After doing some googling i found the solution(It perfectly correct to my problem).
The solution i'm explaining here. It may be helpful to the others.
please check my previous post for the problem .It has subject line:Xpath Namespace problem
Solution is:
public class XMLParsing {
public static void main(String[] args)
{
try {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("E:\\sample.xml");
NamespaceContext ctx = new NamespaceContext() {
public String getNamespaceURI(String prefix) {
String uri;
if (prefix.equals("ns0"))
uri = "http://www.oracle.bt.bp.osm/GPRLN";
else if (prefix.equals("ns2"))
uri = "http://www.davber.com/sales-format";
else
uri = null;
return uri;
}
public Iterator getPrefixes(String val) {
return null;
}
// Dummy implemenation - not used!
public String getPrefix(String uri) {
return null;
}
};
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
xpath.setNamespaceContext(ctx);
XPathExpression fax = xpath.compile("//ns0:Port_and_Routing_Details_g/ns0:Action_Code/ns0:Code3/text()");
Object result = fax.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
int len = nodes.getLength();
System.out.println(len);
for (int i=0; i<len;i++){
System.out.println(nodes.item(i).getNodeValue());
}
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch(SAXException e){
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
catch(XPathExpressionException e){
e.printStackTrace();
}
}
}
After applying the BOLDED Code my problem simply resolved
|
 |
Martijn Verburg
author
Bartender
Joined: Jun 24, 2003
Posts: 3268
|
|
Hi there!
Thanks for posting this to help others, however in future you can probably reply to the original topic (so that it's all together) and also use the code button to syntax highlight your code, easier to read for everyone!
Thanks again
|
Cheers, Martijn - Blog,
Twitter, PCGen, Ikasan, My The Well-Grounded Java Developer book!,
My start-up.
|
 |
 |
|
|
subject: java Xpath Namespace problem Resolved
|
|
|