SVM
SVM

Reputation: 11

Get Child node by attribute value from XML using Java

<?xml version="1.0"?>
<AllConcepts>
    <Level id="1">
        <TST>RegisterPatient</TST>
    </Level>
    <Level id="2">
        <TST>PersonwithInpatientEncounter</TST> 
        <TST>InpatientwithDiagnoses</TST> 
        <TST>InpatientwithRadiologyOrder</TST>      
    </Level>
    <Level id="3">
        <TST>InpatientwithProblem</TST> 
        <TST>InpatientwithAllergy</TST>             
    </Level>
</AllConcepts>

Above is my XML. Please help me to get child node id by giving value in Java.

Example:

Upvotes: 1

Views: 1248

Answers (2)

SomeDude
SomeDude

Reputation: 14238

You could use java.xml.xpath - no need to install third party libs.

and use this xpath to get desired element given a TST value.

//TST[.='<value>']/parent::Level

where <value> could be RegisterPatient or InpatientwithDiagnoses or anything.

Refer to java's xpath documentation here.

Upvotes: 0

Ben Dworkin
Ben Dworkin

Reputation: 400

I would suggest using SAAJ!

It is a great Java library that gives us Java functionality to XML documents. You can use this library to construct, edit, or make SOAP messages. From there you can extract what is needed once that SOAP object is created.

Here is what you can use to create that java object:

// Use SAAJ to convert Document to SOAPElement
// Create SoapMessage
SOAPMessage message = createSOAPMessage();
SOAPBody soapBody = message.getSOAPBody();
// This returns the SOAPBodyElement
SOAPElement xml = soapBody.addDocument(doc);

And then something like this to get content from the XML body:

java.util.Iterator iterator = soapBody.getChildElements(bodyName);
SOAPBodyElement bodyElement = (SOAPBodyElement)iterator.next();
String node = bodyElement.getValue();

References:
https://docs.oracle.com/javase/7/docs/api/javax/xml/soap/SOAPMessage.html https://docs.oracle.com/javaee/5/tutorial/doc/bnbhr.html#bnbhz

Upvotes: 1

Related Questions