bean结构简单如下 Java代码 收藏代码
public class User {
private int count;
private List<Map<String, String>> rows;
}
getter、setter省略 如何才能序列化成下面的格式 Java代码 收藏代码
<user>
<count></count>
<rows>
<row>
<id></id>
<name></name>
</row>
<row>
<id></id>
<name></name>
</row>
</rows>
<user>
其中id、name为Map中的Key。 望各位不吝赐教,谢谢
Java代码 收藏代码
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
@XmlRootElement(name = "user")
@XmlAccessorType(XmlAccessType.FIELD)
public class User {
/**
*
*JAXB XML适配器
*
*/
public static class UserRowsXmlAdapter extends
XmlAdapter<Object, List<Map<String, String>>> {
/**
* 把 JAVA转化成ELEMENT对象
*/
@Override
public Object marshal(List<Map<String, String>> rows) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.newDocument();
Element rootElement = document.createElement("myrows");// 这里名字随便,以外面为准,JAXB会自动替换名字的
document.appendChild(rootElement);
for (Map<String, String> row : rows) {
Element rowEle = document.createElement("row");
Element idEle = document.createElement("id");
Element nameEle = document.createElement("name");
Entry<String, String> entry = row.entrySet().iterator().next();// 第一个ENTRY
String id = entry.getKey();// ID
String name = entry.getValue();// NAME
idEle.setTextContent(id);
nameEle.setTextContent(name);
rowEle.appendChild(idEle);
rowEle.appendChild(nameEle);
rootElement.appendChild(rowEle);
}
return rootElement;
}
/**
* 把XML ELEMENT转化成JAVA对象
*/
@Override
public List<Map<String, String>> unmarshal(Object rowsElement)
throws Exception {
if (rowsElement == null) {
return null;
}
Element rowsEle = (Element) rowsElement;
NodeList rowNodes = rowsEle.getChildNodes();
int rowCount = (rowNodes == null ? 0 : rowNodes.getLength());
if (rowCount == 0) {
return null;
}
List<Map<String, String>> result = new ArrayList<Map<String, String>>(
rowCount);
for (int i = 0; i < rowCount; i++) {
Node rowNode = rowNodes.item(i);
if (!"row".equals(rowNode.getNodeName())) {
System.out.println("发现非法节点:" + rowNode.getNodeName()
+ "忽略.");
continue;
}
NodeList idNameNodes = rowNode.getChildNodes();
int nodeSize = (idNameNodes == null ? 0 : idNameNodes
.getLength());
if (nodeSize == 0) {
continue;
}
Map<String, String> row = new HashMap<String, String>();
String id = null;
String name = null;
for (int j = 0; j < nodeSize; j++) {
Node node = idNameNodes.item(j);
String nodeName = node.getNodeName();
String nodeValue = node.getTextContent();
if ("id".equals(nodeName)) {
id = nodeValue;
} else if ("name".equals(nodeName)) {
name = nodeValue;
}
if (id != null && name != null) {
break;
}
}
if (id != null) {
row.put(id, name);
} else {
System.out.println("未在row节点里发现id节点,忽略.");
}
result.add(row);
}
return result;
}
}
@XmlElement(name="count")
private int count;
@XmlElement(name="rows")
@XmlJavaTypeAdapter(UserRowsXmlAdapter.class)
private List<Map<String, String>> rows;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public List<Map<String, String>> getRows() {
return rows;
}
public void setRows(List<Map<String, String>> rows) {
this.rows = rows;
}
@Override
public String toString() {
return "User [count=" + count + ", rows=" + rows + "]";
}
public static void main(String[] args) throws JAXBException {
User u = new User();
List<Map<String, String>> rows = new ArrayList<Map<String, String>>(2);
Map<String, String> row = new HashMap<String, String>();
row.put("1", "土豆");// userid=1,username=土豆
rows.add(row);
row = new HashMap<String, String>();
row.put("2", "洋葱");// userid=2,username=洋葱
rows.add(row);
u.setCount(rows.size());
u.setRows(rows);
JAXBContext jc = JAXBContext.newInstance(User.class);
StringWriter writer = new StringWriter();
jc.createMarshaller().marshal(u, writer);
System.out.println("Marshalled xml==>");
System.out.println(writer);
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<user><count>2</count><rows><row><id>1</id><name>土豆</name>"
+ "</row><row><id>2</id><name>洋葱</name>"
+ "</row></rows></user>";
User newu = (User) jc.createUnmarshaller().unmarshal(
new StringReader(xml));
System.out.println("UnMarshalled user==>");
System.out.println(newu);
}
}
输出结果:
Java代码 收藏代码
Marshalled xml==>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><user><count>2</count><rows><row><id>1</id><name>土豆</name></row><row><id>2</id><name>洋葱</name></row></rows></user>
UnMarshalled user==>
User [count=2, rows=[{1=土豆}, {2=洋葱}]]
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。