Reputation: 329
I have tried Jackson API to parse below XML into java object but it did not work. I only want object that represents the student record . Can anybody help me with this? For standard xml format, the Jackson API works but for the below example I am not able to do so
<?xml version="1.0" encoding="utf-8"?>
<DataTable xmlns="http://*****.com">
<xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="StudentRecord" msdata:UseCurrentLocale="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="StudentRecord">
<xs:complexType>
<xs:sequence>
<xs:element name="StudentId" type="xs:string" minOccurs="0" />
<xs:element name="FName" type="xs:string" minOccurs="0" />
<xs:element name="LName" type="xs:string" minOccurs="0" />
<xs:element name="Address1" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
<DocumentElement xmlns="">
<StudentRecord diffgr:id="StudentRecord1" msdata:rowOrder="0">
<StudentId>&&&&&&&</StudentId>
<FName>ABC</FName>
<LName>DSF</LName>
<Address1>12345</Address1>
</StudentRecord>
</DocumentElement>
</diffgr:diffgram>
</DataTable>
Upvotes: 2
Views: 749
Reputation: 325
SimpleXml can do it, first 1 POJO:
public class StudentRecord {
@XmlAttribute
@XmlName("diffgr:id")
public String id;
@XmlAttribute
@XmlName("msdata:rowOrder")
public int rowOrder;
@XmlName("StudentId")
public String studentId;
@XmlName("FName")
public String firstName;
@XmlName("LName")
public String lastName;
@XmlName("Address1")
public String address1;
}
Next we turn the XML into a DOM, then we grab the element we need and convert that element to our class.
final SimpleXml simple = new SimpleXml();
final Element root = simple.fromXml(xml);
final StudentRecord student = simple.fromXml(root.children.get(1).children.get(0).children.get(0), StudentRecord.class);
System.out.println(student.id + " : " + student.firstName + " " + student.lastName);
This code will print:
StudentRecord1 : ABC DSF
SimpleXml is in maven central:
<dependency>
<groupId>com.github.codemonstur</groupId>
<artifactId>simplexml</artifactId>
<version>1.5.5</version>
</dependency>
Upvotes: 3