I think the easiest way, without explicitly parsing the XML text, would be using JAXB as follows. Create a Detail class that only has annotated the variables that you want to load from the input XML.
For an input.xml file, which not only contains firstname and lastname, but also other XML elements (as requested in the comments):
<?xml version="1.0" encoding="UTF-8"?>
<Detail>
<firstname>firstname</firstname>
<lastname>lastname</lastname>
<elementA>element A</elementA>
<elementB>element B</elementB>
<elementC>element C</elementC>
</Detail>
If you have a Detail class with only firstname and lastname annotated as follows:
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "Detail")
@XmlType(propOrder = { "firstname", "lastname"})
public class Detail {
@XmlElement(name="firstname")
private String firstname;
@XmlElement(name="lastname")
private String lastname;
private String elementA = "default elementA";
private String elementB = "default elementB";
private String elementC = "default elementC";
public Detail(){}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getElementA() {
return elementA;
}
public void setElementA(String elementA) {
this.elementA = elementA;
}
public String getElementB() {
return elementB;
}
public void setElementB(String elementB) {
this.elementB = elementB;
}
public String getElementC() {
return elementC;
}
public void setElementC(String elementC) {
this.elementC = elementC;
}
}
and also a jaxb.index file, located in the same folder as the compiled classes, whose only content is:
Detail
and you test your input XML like this:
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class Test {
public static void main(String[] args) {
try{
JAXBContext jc = JAXBContext.newInstance(Detail.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("input.xml");
Detail detail = (Detail) unmarshaller.unmarshal(xml);
System.out.println("Detail firstname:"+detail.getFirstname()+" lastname:"+detail.getLastname());
}
catch(JAXBException e){
System.out.println(e.getMessage());
}
}
}
You will see that Detail has only firstname and lastname loaded from the XML file.