简体   繁体   English

如何在 Java 中迭代 Xml 文件并从中创建对象

[英]How to iterate Xml file in Java and create objects from it

I have a Xml file which I iterate like this:我有一个 Xml 文件,我像这样迭代它:

List<String> list = new ArrayList<>();

for (int i = 0; i < nList.getLength(); i++) {

        Node nNode = nList.item(i);

        System.out.println("\nCurrent Element: " + nNode.getNodeName());

        if (nNode.getNodeType() == Node.ELEMENT_NODE) {

            Element elem = (Element) nNode;

            Node id = elem.getElementsByTagName("id").item(0);
            Node key = elem.getElementsByTagName("key").item(0);
            if (id.getTextContent().length() > 0) {
                String identifier = id.getTextContent();
                String key2 = key.getTextContent();

                System.out.println("id: " + identifier);
                System.out.println("key: " + key2);

                list.add(identifier);
                list.add(key2);

            }
        }
    }

That works and as you can see, I can add the values to a list of Strings but that's not what I want to do.这行得通,如您所见,我可以将值添加到字符串列表中,但这不是我想要做的。 I want to make a list of objects from those string values, lke this:我想从这些字符串值中创建一个对象列表,例如:

[{"id": identifier, "key": key2}] . [{"id": identifier, "key": key2}]

I've tried many ways but nothing seems to work, there must be some simple way in Java also to add those strings as a key-value pairs in a list?我尝试了很多方法,但似乎没有任何效果,Java 中必须有一些简单的方法也可以将这些字符串作为键值对添加到列表中?

Here:这里:

List<String> list = new ArrayList<>();

If you dont want to collect Strings , then say so:如果您不想收集Strings ,请这样说:

List<Map<String, String>> list = new ArrayList<>();

And then, instead of adding strings:然后,而不是添加字符串:

list.add(identifier);
list.add(key2)

You could do:你可以这样做:

list.add(Collections.singletonMap(identifier, key2);

or something alike.或类似的东西。

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

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