hashmap xml
时间: 2023-11-08 12:48:33 浏览: 91
hashmap 实例
3星 · 编辑精心推荐
HashMap是Java中的一个常用数据结构,用于存储键值对。如果需要将HashMap序列化成XML格式,可以使用Java中提供的XML API,如JAXB或XStream。
使用JAXB:
1. 创建HashMap对象,并添加键值对
```
HashMap<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
```
2. 创建一个包含HashMap对象的类,使用@XmlRootElement注解标注
```
import java.util.HashMap;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class MapWrapper {
private HashMap<String, String> map;
public MapWrapper() {}
public MapWrapper(HashMap<String, String> map) {
this.map = map;
}
public HashMap<String, String> getMap() {
return map;
}
public void setMap(HashMap<String, String> map) {
this.map = map;
}
}
```
3. 使用JAXBContext创建一个Marshaller对象,将MapWrapper对象序列化为XML格式
```
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;
JAXBContext context = JAXBContext.newInstance(MapWrapper.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
MapWrapper wrapper = new MapWrapper(map);
StringWriter writer = new StringWriter();
marshaller.marshal(wrapper, writer);
String xmlString = writer.toString();
```
使用XStream:
1. 创建HashMap对象,并添加键值对
```
HashMap<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
```
2. 创建XStream对象,并使用toXML方法将HashMap序列化为XML格式
```
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
XStream xstream = new XStream(new DomDriver());
String xmlString = xstream.toXML(map);
```
注意:使用XStream序列化时,需要引入相关依赖,如下所示:
```
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.11</version>
</dependency>
```
阅读全文