Answer the question
In order to leave comments, you need to log in
How to parse an XML document using a DOM parser if we need to get data not of type String, but for example Date?
There is an XML document:
<car>
<name>Volvo</name>
<date_make>04.02.1971</date_make>
</car>
public class Car {
private String name;
private Date make;
public void setName(String name) {
this.name = name;
}
public void setMake(Date make) {
this.make = make;
}
}
file = "location";
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(file);
NodeList nodeList = doc.getDocumentElement().getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node instanceof Element) {
Car obj = new Car();
NodeList childNodes = node.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
Node cNode = childNodes.item(j);
if (cNode instanceof Element) {
String name = cNode.getLastChild().getTextContent();
Date content1 = ?????; //для текстового содержимого есть метод getTextContent(), а что делать если содержимое типа Date
String str = cNode.getNodeName();
switch (str) {
case "name":
obj.setName(content);
break;
case "date_make":
obj.setMake(content1);
break;
}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question