ortnm12
ortnm12

Reputation: 3

Get specific element from xml file

Let's say i have two xml files. Both contain a specific element (let's say "name") but one has the element on a different position than the other xml file.

ex:

first xml-file:

<root>
 <element1>text1</element1>
 <element2>
  <name value="firstname">John</name>
 <element2>
</root>

second xml-file:

<root>
 <element1>text1</element1>
 <name value="firstname">Michael</name>
 <element2>text2</element2>
</root>

what is the most runtime-efficient way to get this elements without knowing their position before?

(Sorry if there is already an answer on stackoverflow but I didn't find one)

Upvotes: 0

Views: 366

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477881

A not necessarily most efficient, but more convenient way to do this is making use of XPath queries:

File f = new File("path/to/file.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(f);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//name");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

The query:

"//name"

means:

Search for all <name> tags, regardless of their depth. You can then process the NodeList.

Although there is some overhead involved with XPath queries, the current technologies are in many cases sufficient and furthermore it is easy to modify the queries (what if for some reason you must slightly modify the query?).

Upvotes: 1

BMac
BMac

Reputation: 2240

You might want to investigate Xpath. see How to read XML using XPath in Java for your specific case the xpath will be "//name" double / means anywhere is the current document from root.

Upvotes: 2

Related Questions