• Post Reply Bookmark Topic Watch Topic
  • New Topic

java Xpath Namespace problem Resolved  RSS feed

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
author
Bartender
Posts: 3275
5
Eclipse IDE Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!