Solved

Programmatically obtaining the XPATH of an XML Node : Java 1.4

Posted on 2006-11-30
3
793 Views
Last Modified: 2008-02-26
Hi All

Given an XML document and any given node inside the XML, how do I obtain the XPATH for that particular node from the 'root' node using Java code ?

For instance, if I have an XML like this

<root>
  <level1>
    <sublevel11> sss </sublevel11>
    <sublevel12>
         <sublevel12A> xxx </sublevel12A>
         <sublevel12B> xxx </sublevel12B>
    </sublevel12>
  </level1>
</root>

Now, when I am at <sublevel12A>, I need my output as "root/level1/sublevel12/sublevel12A".

How do I write Java code that can do this ?

Thanks in Advance !
0
Comment
Question by:netuser1976
3 Comments
 
LVL 12

Accepted Solution

by:
enachemc earned 200 total points
Comment Utility
<root>
  <level1>
    <sublevel11> sss </sublevel11>
    <sublevel12>
         <sublevel12A> xxx </sublevel12A>
         <sublevel12B> xxx </sublevel12B>
    </sublevel12>
    <sublevel12>
         <sublevel12A> xxx </sublevel12A>
         <sublevel12B> xxx </sublevel12B>
    </sublevel12>
  </level1>
</root>

if the above is the XML in cause, then you XPath would fail ... as there are 2 XML elements that match the required name. You will have to do something like: /root/level1[position()=1]/sublevel12[position()=1]/sublevel12A[position()=1]

You will have to start from the node, write it's position in the parent, then continue with it's parent in a while loop (iterating through parents until the root is reached - it has no parent).
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
Many times as a report developer I've been asked to display normalized data such as three rows with values Jack, Joe, and Bob as a single comma-separated string such as 'Jack, Joe, Bob', and vice versa.  Here's how to do it. 
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now