How do I find an XmlDocument Element?

May 20th, 2008 by stevi | Filed under Java

We’re using XMLBeans as part of a project. I had a document called EventConfig that had many EventDetails. I needed to find one EventDetails element based on its child element, EventName.

Being new to XMLBeans, and in bug fixing mode, I checked the XmlObject API, and saw only that selectPath(String) took a String. I couldn’t find an example of what syntax to use to do this kind of a search.

The answer is XPath 2.0 (which is noted in the Javadoc for the method, but I didn’t understand what it meant at the time).

As usual, I found the W3C documentation to be a bit overwhelming. But I did find this XPath Tutorial which gave the correct syntax for XPath Predicates, which enable us to select specific nodes. Predicates are embedded in square brackets. So for my case, I could find my EventDetails based on the EventName.

public EventDetails findDetails(String eventName) {
    EventDetails eventDetails = null;
    String queryExpression = 
        String.format(
        "declare namespace po = 'http://www.stevideter.com/project/eventconfig';$this/po:EventInfo/EventDetails[EventName='%s']",eventName);
    EventDetails[] eventDetailsArray = (EventDetails[]) EventConfig.selectPath(queryExpression);
    if (eventDetailsArray != null && eventDetailsArray.length > 0) { 
        eventDetails = eventDetailsArray[0];
    }
    return eventDetails;
}

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

tag_iconTags: | |

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a comment.

To leave a comment, please fill in the fields below.