kaleeway kaleeway - 1 year ago 69
Java Question

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


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:


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>


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 with attribute value

The expression is not working:


Any ideas what I am doing wrong?

Answer Source

Try this:


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: