0

I have a xpath of an element and need to write a java code which gives me exactly the same element as an object. I believe i need to use SAX or DOM ? i m totally newbie..

xpath :

/*[local-name(.)='feed']/*[local-name(.)='entry']/*[local-name(.)='title']
Akin Dönmez
  • 353
  • 8
  • 24
  • What exactly do you mean by "gives me" the element? Do you want to extract it as XML to a string or a file, or do you want it as a Java object in some object model (there are many to choose from, W3C DOM, JDOM, DOM4J, XOM, etc., all of which support XPath to some degree). – Ian Roberts Jan 20 '15 at 17:22
  • Well, i just have a task which i supposed to write a java code that does the same thing as this xpath code..Yeah as a DOM4J object in java.. – Akin Dönmez Jan 20 '15 at 18:18

2 Answers2

0

Your comment suggests you want to use DOM4J, which supports XPath out of the box:

SAXReader reader = new SAXReader();
Document doc = reader.read(new File(....)); // or URL, or wherever the XML comes from
Node selectedNode = doc.selectSingleNode("/*[local-name(.)='feed']/*[local-name(.)='entry']/*[local-name(.)='title']");

(or there's also selectNodes which returns a List, if there might be more than one node matching that XPath expression - quite likely if this is an Atom feed).

But rather than using the local-name hack like this, if you know the namespace URI of the elements in your XML you can declare a prefix for this namespace and select the nodes by their fully qualified name:

SAXReader reader = new SAXReader();
Map<String, String> namespaces = new HashMap<>();
namespaces.put("atom", "http://www.w3.org/2005/Atom");
reader.getDocumentFactory().setXPathNamespaceURIs(namespaces);

Document doc = reader.read(new File(....)); // or URL, or wherever the XML comes from
List selectedNodes = doc.selectNodes("/atom:feed/atom:entry/atom:title");
Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
0

read here: https://howtodoinjava.com/java/xml/java-xpath-tutorial-example/

I found it while I were searching to find how to convert Xpath PMD-rule to java-rule,, I did not find what I need in it. but, anyway may be you can find yours.

AvaEng
  • 1
  • 1
  • 1
    Please don't post external links as answers, as they may go out of data or disappear. It's better to summarise the answer in the body itself. – AlBlue Nov 02 '20 at 21:50