1

How could you pull data from an XML file and insert into a Java array or array list?

A sample of the XML file below that I would like to import into an array:

<dataset>
    <record>
    <id>1</id>
    <full_name>Ernestus Ellins</full_name>
    </record>
    <record>
    <id>2</id>
    <full_name>Tyson Haysey</full_name>
       </record>
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
indo3933
  • 11
  • 1

2 Answers2

0
 String xml = "<dataset><record>\n" +
            "<id>1</id>\n" +
            "<full_name>Ernestus Ellins</full_name>\n" +
            "</record>\n" +
            "<record>\n" +
            "<id>2</id>\n" +
            "<full_name>Tyson Haysey</full_name>\n" +
            "   </record></dataset>";
 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 DocumentBuilder builder = factory.newDocumentBuilder();
 InputSource is = new InputSource( new StringReader(xml) );
 Document doc = builder.parse( is );
 XPathFactory factoryPath = XPathFactory.newInstance();
 XPath xpath = factoryPath.newXPath();
 XPathExpression exprIds = xpath.compile("//id/text()");
 XPathExpression exprFullName = xpath.compile("//full_name/text()");

 Object ids = exprIds.evaluate(doc, XPathConstants.NODESET);
 Object fullNames = exprFullName.evaluate(doc, XPathConstants.NODESET);
 NodeList nodesIds = (NodeList) ids;
 NodeList nodesFullNames = (NodeList) fullNames;

 List<Record> records = new ArrayList<>();
 for (int i = 0; i < nodesIds.getLength(); i++) {
     records.add (new Record(Integer.parseInt(nodesIds.item(i).getNodeValue()), nodesFullNames.item(i).getNodeValue()));
 }
 System.out.println(records);

Record class in my example:

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@AllArgsConstructor
@ToString
public class Record {
    private int id;
    private String fullName;
}
mcieciel
  • 59
  • 3
0

I recommend you to use the JAXB framework, which allows you to fill POJOs from XML and viceversa, i.e., create XML from POJOs. These operations are called "unmarshalling" and "marshalling," respectively. You can find a complete description of JAXB here and examples of its application at this link.

You should also use XJC, which permits you to automatically generate Java classes from XSD files (which represent the structure of the XML). If you are not confident with XSD files, you can generate them from your XML (there are a lot of online tools).

Once you have created the Java classes from XSD and unmarshalled the XML file, you can manipulate your XML using standard Java.