Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath search by "id" attribute , giving NPE - Java

Tags:

java

xml

xpath

All,

I have multiple XML templates that I need to fill with data, to allow my document builder class to use multiple templates and insert data correctly

I designate the node that I want my class to insert data to by adding an attribute of:

id="root"

One example of an XML

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> <SiebelMessage MessageId="07f33fa0-2045-46fd-b88b-5634a3de9a0b" MessageType="Integration Object" IntObjectName="" IntObjectFormat="Siebel Hierarchical" ReturnCode="0" ErrorMessage="">     <listOfReadAudit >         <readAudit id="root">             <recordId mapping="Record ID"></recordId>             <userId mapping="User ID"></userId>             <customerId mapping="Customer ID"></customerId>             <lastUpd mapping="Last Updated"></lastUpd>             <lastUpdBy mapping="Last Updated By"></lastUpdBy>             <busComp mapping="Entity Name"></busComp>         </readAudit>     </listOfReadAudit> </SiebelMessage> 

Code

expr = xpath.compile("//SiebelMessage[@id='root']"); root = (Element) expr.evaluate(xmlDoc, XPathConstants.NODE); Element temp = (Element) root.cloneNode(true); 

Using this example: XPath to select Element by attribute value

The expression is not working:

//SiebelMessage[@id='root']

Any ideas what I am doing wrong?

like image 465
tomaytotomato Avatar asked Mar 21 '14 10:03

tomaytotomato


People also ask

How do I navigate to parent node in XPath?

A Parent of a context node is selected Flat element. A string of elements is normally separated by a slash in an XPath statement. You can pick the parent element by inserting two periods “..” where an element would typically be. The parent of the element to the left of the double period will be selected.

What is XPath parsing?

It defines a language to find information in an XML file. It is used to traverse elements and attributes of an XML document.


2 Answers

Try this:

//readAudit[@id='root'] 

This selects all readAudit elements with the id attribute set to root (it should be just 1 element in your case).

You could make sure it returns maximum 1 element with this:

//readAudit[@id='root'][1] 
like image 135
Stefan Pries Avatar answered Sep 20 '22 16:09

Stefan Pries


What you are doing is selecting SiebelMessage nodes with the attribute id='root'.

But the SiebelMessage doesn't have an id, it's the readAudit you are after. So either do

//readAudit[id='root'] 

or

//SiebelMessage//readAudit[id='root'] 
like image 32
kutschkem Avatar answered Sep 23 '22 16:09

kutschkem