I have a sample XML document with many child tags. It is shown below
Since there are multiple types, I want to pass it to the collection as an object. So I create a custom class StudentsType as shown below:
Now since i want to pass it to the collection (List) as objects, I do not seem to find a way to get it working.
Any concept or ideas that I could brush or use?
XML:
<?xml version="1.0"?>
<Students>
<StudentX>
<Name>A</Name>
<Age>15</Age>
<Subjects>
<Subject type = "M">English</Subject>
<Subject type = "M">Hindi</Subject>
<Subject type = "O">Kannada</Subject>
<Subject type = "O">Social</Subject>
<Subject type = "M">MATH</Subject>
<Subject type = "M">Science</Subject>
</Subjects>
</StudentX>
<StudentY>
<Name>D</Name>
<Age>15</Age>
<Subjects>
<Subject type = "M">English</Subject>
<Subject type = "M">French</Subject>
<Subject type = "O">Kannada</Subject>
<Subject type = "O">SUPW</Subject>
<Subject type = "M">MATH</Subject>
<Subject type = "M">Science</Subject>
</Subjects>
</StudentY>
<StudentZ>
<Name>S</Name>
<Age>15</Age>
<Subjects>
<Subject type = "M">English</Subject>
<Subject type = "M">MentalStrength</Subject>
<Subject type = "O">Kannada</Subject>
<Subject type = "O">SUPW</Subject>
<Subject type = "M">Softskills</Subject>
<Subject type = "M">Science</Subject>
</Subjects>
</StudentZ>
</Students>
Since there are multiple types, I want to pass it to the collection as an object. So I create a custom class StudentsType as shown below:
Java:
import java.awt.List;
import java.util.ArrayList;
import lombok.Data;
@Data
public class StudentsType {
private String Name;
private int Age;
private ArrayList<String> subjects = new ArrayList<String>();
}
Now since i want to pass it to the collection (List) as objects, I do not seem to find a way to get it working.
Java:
public class ParsingXML {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<StudentsType> listOfStudentsType= new ArrayList<StudentsType>();
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder =factory.newDocumentBuilder();
Document doc= builder.parse("SimpleStudent.xml");
NodeList listOfNodes= doc.getDocumentElement().getChildNodes();
for(int i =0; i < listOfNodes.getLength();i++) {
//looking for some generic code here to pass the object to the collection
}
}
log.info("numberOfChild: "+listOfNodes.getLength());
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Any concept or ideas that I could brush or use?