ravi ch
ravi ch

Reputation: 31

Get Parent attribute value based XML search using xpath java

I want get RECORD number based on contract id passed to java method. can any one help on this as i am new to XML parsing?

sample xml file:

<?xml version="1.0"?><FILE>
<Document RECORD="1"><Contract-Id>234</Contract-Id><Client-Id>232</Client-Id></Document>
<Document RECORD="2"><Contract-Id>235</Contract-Id><Client-Id>334</Client-Id></Document>
</FILE?

Java code:

              File fXmlFile = new File(inputFile);
               DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
               DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
               Document xmlDocument = dBuilder.parse(fXmlFile);
               xmlDocument.getDocumentElement().normalize();
   
    
        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression xPathExpr = xPath.compile("//Document/Contract-Id[text()='"+ContractNumber+"']");
        //Object result = xPathExpr.evaluate(xmlDocument,XPathConstants.NODESET);
        
        Node nl = (Node)xPathExpr.evaluate(xmlDocument.getParentNode(), XPathConstants.NODESET);
        nl.getTextContent();
        nl.getAttributes();

    

Upvotes: 2

Views: 42

Answers (1)

Yitzhak Khabinsky
Yitzhak Khabinsky

Reputation: 22187

Please try the following XPath expression:

/FILE/Document[Contract-Id="235"]/@RECORD

Upvotes: 1

Related Questions