-1

I basically want to know how to get these element values from the xml file in java set it into the Object.

Below are the sample XML file

<?xml version="1.0" encoding="UTF-8"?>
<Response>
   <LoanApplication>
      <LoanId>1111</LoanId>
      <LoanStatus>Unsuccessful</LoanStatus>
      <LoanReference>111</LoanReference>
   </LoanApplication>
   <LoanApplication>
      <LoanId>222</LoanId>
      <LoanStatus>Unsuccessful</LoanStatus>
      <LoanReference>333</LoanReference>
   </LoanApplication>
   <LoanApplication>
      <LoanId>222</LoanId>
      <LoanStatus>Unsuccessful</LoanStatus>
      <LoanReference>4444</LoanReference>
   </LoanApplication>
   <LoanApplication>
      <LoanId>555</LoanId>
      <LoanStatus>Current</LoanStatus>
      <LoanReference>7777</LoanReference>
   </LoanApplication>
   <LoanApplication>
      <LoanId>3333</LoanId>
      <LoanStatus>Current</LoanStatus>
      <LoanReference>9999</LoanReference>
   </LoanApplication>
</Response>   

Below are the Class where I want get xml data...

public class LoanIDResponse implements java.io.Serializable
{
private Integer loanID;
private Integer loanReference;
private String loanStatus;

public LoanIDResponse()
{
}
public void setLoanID(Integer loanID)
{
    this.loanID = loanID;
}

public void setLoanStatus(String loanStatus)
{
    this.loanStatus = loanStatus;
}

public void setLoanReference(Integer loanReference)
{
    this.loanReference = loanReference;
}
public Integer getLoanID()
{
    return loanID;
}

public Integer getLoanReference()
{
    return loanReference;
}

public String getLoanStatus()
{
    return loanStatus;
}
}

Below are the method where put some effort to parse xml file. Now I am struck how to set in my class setters.

 public Set<LoanIDResponse> getLoanIDList()
    {
        Set<LoanIDResponse> loanIDSet = new HashSet<>();
        try
        {

            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(new File("Response.xml"));

            doc.getDocumentElement().normalize();
            NodeList listOfLoanApplication = doc.getElementsByTagName("LoanApplication");
            int totalLoanApplication = listOfLoanApplication.getLength();


            for (int s = 0; s < listOfLoanApplication.getLength(); s++)
            {

                Node loanApplicationNode = listOfLoanApplication.item(s);
                if (loanApplicationNode.getNodeType() == Node.ELEMENT_NODE)
                {
                    LoanIDResponse response = new LoanIDResponse();
                    Element loanApplicationElement = (Element) loanApplicationNode;

                    NodeList loanIDList = loanApplicationElement.getElementsByTagName("LoanId");

                    NodeList loanReferenceList = loanApplicationElement.getElementsByTagName("LoanReference");

                    NodeList loanStatusList = loanApplicationElement.getElementsByTagName("LoanStatus");

                }

            }

        } catch (SAXParseException err)
        {
            LOGGER.log(Level.WARNING, "** Parsing error" + ", line {0}, uri {1}", new Object[]
            {
                err.getLineNumber(), err.getSystemId()
            });
            LOGGER.log(Level.WARNING, " {0}", err.getMessage());

        }
        return loanIDSet;
    }
Z.U.H
  • 325
  • 2
  • 13

2 Answers2

2

Start by having a look at Introduction to JAXB and Java API for XML Processing (JAXP) for more details.

This example works on JAXB

First, you need some classes to hold your data

LoanApplication

This is the basic properties of the loan application

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "LoanApplication")
public class LoanApplication {
    private long loanId;
    private String loanStatus;
    private long loadReference;

    public long getLoanId() {
        return loanId;
    }

    public String getLoanStatus() {
        return loanStatus;
    }

    public long getLoadReference() {
        return loadReference;
    }

    @XmlElement(name="LoanId")
    public void setLoanId(long loanId) {
        this.loanId = loanId;
    }

    @XmlElement(name="LoanStatus")
    public void setLoanStatus(String loanStatus) {
        this.loanStatus = loanStatus;
    }

    @XmlElement(name="LoanReference")
    public void setLoadReference(long loadReference) {
        this.loadReference = loadReference;
    }

    @Override
    public String toString() {
        return getLoanId() + "; " + getLoanStatus() + "; " + getLoadReference();
    }
}

Response

This is a "container" class which contains a list of LoanApplications

import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Response")
public class Response {

    private List<LoanApplication> applications;

    @XmlElement(name="LoanApplication")
    public void setApplications(List<LoanApplication> applications) {
        this.applications = applications;
    }

    public List<LoanApplication> getApplications() {
        return applications;
    }

}

Reading...

Then we can read the XML file using something like...

try {
    File file = new File("Responses.xml");
    JAXBContext jaxbContext = JAXBContext.newInstance(Response.class);

    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    Response response = (Response) jaxbUnmarshaller.unmarshal(file);
    for (LoanApplication app : response.getApplications()) {
        System.out.println(app);
    }
} catch (JAXBException ex) {
    ex.printStackTrace();
}

which based on the my example code, outputs

1111; Unsuccessful; 111
222; Unsuccessful; 333
222; Unsuccessful; 4444
555; Current; 7777
3333; Current; 9999

Writing...

Writing is pretty much as the same as reading, in fact, for this example, it will include the reading portion as well, so we can update the content...

try {
    File file = new File("Responses.xml");
    JAXBContext jaxbContext = JAXBContext.newInstance(Response.class);

    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    Response response = (Response) jaxbUnmarshaller.unmarshal(file);
    for (LoanApplication app : response.getApplications()) {
        System.out.println(app);
    }

    LoanApplication app = new LoanApplication();
    app.setLoadReference(123456);
    app.setLoanId(7890);
    app.setLoanStatus("Approved");
    response.getApplications().add(app);

    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    jaxbMarshaller.marshal(response, new File("Responses.xml"));
    //jaxbMarshaller.marshal(response, System.out);
} catch (JAXBException ex) {
    ex.printStackTrace();
}

Which generates...

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Response>
    <LoanApplication>
        <LoanReference>111</LoanReference>
        <LoanId>1111</LoanId>
        <LoanStatus>Unsuccessful</LoanStatus>
    </LoanApplication>
    <LoanApplication>
        <LoanReference>333</LoanReference>
        <LoanId>222</LoanId>
        <LoanStatus>Unsuccessful</LoanStatus>
    </LoanApplication>
    <LoanApplication>
        <LoanReference>4444</LoanReference>
        <LoanId>222</LoanId>
        <LoanStatus>Unsuccessful</LoanStatus>
    </LoanApplication>
    <LoanApplication>
        <LoanReference>7777</LoanReference>
        <LoanId>555</LoanId>
        <LoanStatus>Current</LoanStatus>
    </LoanApplication>
    <LoanApplication>
        <LoanReference>9999</LoanReference>
        <LoanId>3333</LoanId>
        <LoanStatus>Current</LoanStatus>
    </LoanApplication>
    <LoanApplication>
        <LoanReference>123456</LoanReference>
        <LoanId>7890</LoanId>
        <LoanStatus>Approved</LoanStatus>
    </LoanApplication>
</Response>

Note the last record is new

I pretty much hobbled it together from this example and this example

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

You can get the node value like ...

 NodeList loanIDList = loanApplicationElement.getElementsByTagName("LoanId");
 Element loanIDElement = (Element) loanIDList.item(0);

 NodeList textIDList = loanIDElement.getChildNodes();
 response.setLoanID(Integer.parseInt(((Node)textIDList.item(0)).getNodeValue().trim()));

//-------
 NodeList loanReferenceList = loanApplicationElement.getElementsByTagName("LoanReference");
 Element loanReferenceElement = (Element) loanReferenceList.item(0);

 NodeList textLRList = loanReferenceElement.getChildNodes();
 response.setLoanReference(Integer.parseInt(((Node) textLRList.item(0)).getNodeValue().trim()));
//-------
 NodeList loanStatusList = loanApplicationElement.getElementsByTagName("LoanStatus");
 Element loanStatusElement = (Element) loanStatusList.item(0);

 NodeList textLSList = loanStatusElement.getChildNodes();
 response.setLoanStatus(((Node) textLSList.item(0)).getNodeValue().trim());
Z.I.J
  • 1,157
  • 16
  • 36