0

What would be the best way to stick this XML into an object?

<root>
    <data value=1>
        <cell a='1' b='0'/>
        <cell a='2' b='0'/>
        <cell a='3' b='0'/>
    </data>
    <data value=12>
        <cell a='2' b='0'/>
        <cell a='4' b='1'/>
        <cell a='3' b='0'/>
    </data>
</root>

We can assume that

  • Each data value will be unique.
  • Actual numeric value assigned to it is important and needs to be captured
  • Actual numbers assigned to data value may come in different order, It won't necessarily be an array of sequential numbers. All we know is that numbers will be unique

Is it possible to put this into Map<Integer, List<Cell>>, grouping cells under the data value?

Ideally method signature would look as follows public static Map<Integer, List<Cell>> parse(String pathToFile)

Would you provide an example please?

2
  • It depends on what you want to capture. Is there always going to be exactly one <data> element below the root? Is the value attribute important? Can they be treated as an array (e.g., are the value attributes sequential)? Commented Sep 29, 2013 at 19:58
  • Right, thank you. I updated the question to hopefully answer it. Commented Sep 29, 2013 at 20:00

1 Answer 1

1

There are lots of examples of XML parsing. The simplest API (definitely not the most efficient) is DOM parsing. Here's one way:

public static Map<Integer, List<Cell>> parse(String pathToFile) {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(pathToFile);
    Map<Integer, List<Cell>> result = new HashMap<>();
    NodeList dataNodes = doc.getElementsByTagName("data");
    int count = dataNodes.getLength();
    for (int i = 0; i < count; ++i) {
        Node node = dataNodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;
            int value = Integer.parseInt(element.getAttribute("value"));
            result.put(value, getCells(element);
        }
    }
    return result;
}

private static List<Cell> getCells(Element dataNode) {
    List<Cell> result = new ArrayList<>();
    NodeList dataNodes = dataNode.getElementsByTagName("cell");
    int count = dataNodes.getLength();
    for (int i = 0; i < count; ++i) {
        // similar to above code
    }
    return result;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ted, Thank you very much indeed!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.