将linkedhashmap转换为DOM元素/ XML

问题描述 投票:0回答:1

我想创建一个方法:给定任何LinkedHashMap,它必须将其转换为Document的XML / Dom元素:

@Override
    public Element marshal(Object linkedHashMap) {

       Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
       final Element element = doc.createElement("root");

       //For each attribute and object of the linked hashmap
       // I must iterate recursively in order to get all the objects and atributes of the LinkedHashMap and append them to the root node element:

       //element.appendChild(...));

      return element; // here the element must be already populated with all the attributes of the linked hashmap and its values.
    }

我不知道该如何实现,如何遍历LinkedHashMap的属性以将它们映射到Element?

我认为我需要这样的东西,但是它必须遍历linkedhashmap的所有级别和子级别(嵌套对象):

Element root = doc.createElement(rootName);
doc.appendChild(root);
for (Map.Entry<String,String> element : map.entrySet() ) {
    Element e = doc.createElement(element.getKey());
    e.setTextContent(element.getValue());
    root.appendChild(e);
}
java xml dom linkedhashmap
1个回答
0
投票
您评论中的关键词是“递归”。 JAXB无法将地图直接序列化为XML,因此您必须为Map的键或值中使用的每种类型提供封送处理程序。

This link can help你那个。

© www.soinside.com 2019 - 2024. All rights reserved.