R
R
roman38472014-06-09 15:52:40
Java
roman3847, 2014-06-09 15:52:40

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>

How to parse this document, if the name of the car needs to be put into the program as a String type, and the production date as a Date type, in order to work with the date later. While there is such code:
There is a class in which the fields of the car are described:
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;
  }
}

The analysis itself:
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 question

Ask a Question

731 491 924 answers to any question