简体   繁体   English

将XML解析为Java对象,需要澄清

[英]Parsing XML to a Java object, clarification needed

What would be the best way to stick this XML into an object? 将XML粘贴到对象中的最佳方法是什么?

<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. 每个data value都是唯一的。
  • 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 ? 是否可以将其放入Map<Integer, List<Cell>> ,对data value下的单元格进行分组?

Ideally method signature would look as follows public static Map<Integer, List<Cell>> parse(String pathToFile) 理想情况下,方法签名应如下所示: public static Map<Integer, List<Cell>> parse(String pathToFile)

Would you provide an example please? 请提供一个例子吗?

There are lots of examples of XML parsing. 有很多XML解析的示例。 The simplest API (definitely not the most efficient) is DOM parsing. 最简单的API(肯定不是最有效的)是DOM解析。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM