简体   繁体   中英

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();

    

Please try the following XPath expression:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM