jaxb代码

来源:互联网 发布:js判断符号不等于 编辑:程序博客网 时间:2024/06/09 17:27
  1. import java.io.StringReader;  
  2. import java.io.StringWriter;  
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7. import java.util.Map.Entry;  
  8.   
  9. import javax.xml.bind.JAXBContext;  
  10. import javax.xml.bind.JAXBException;  
  11. import javax.xml.bind.annotation.XmlAccessType;  
  12. import javax.xml.bind.annotation.XmlAccessorType;  
  13. import javax.xml.bind.annotation.XmlElement;  
  14. import javax.xml.bind.annotation.XmlRootElement;  
  15. import javax.xml.bind.annotation.adapters.XmlAdapter;  
  16. import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;  
  17. import javax.xml.parsers.DocumentBuilder;  
  18. import javax.xml.parsers.DocumentBuilderFactory;  
  19.   
  20. import org.w3c.dom.Document;  
  21. import org.w3c.dom.Element;  
  22. import org.w3c.dom.Node;  
  23. import org.w3c.dom.NodeList;  
  24.   
  25. @XmlRootElement(name = "user")  
  26. @XmlAccessorType(XmlAccessType.FIELD)  
  27. public class User {  
  28.   
  29.     /** 
  30.      *  
  31.      *JAXB XML适配器 
  32.      * 
  33.      */  
  34.     public static class UserRowsXmlAdapter extends  
  35.             XmlAdapter<Object, List<Map<String, String>>> {  
  36.   
  37.         /** 
  38.          * 把 JAVA转化成ELEMENT对象 
  39.          */  
  40.         @Override  
  41.         public Object marshal(List<Map<String, String>> rows) throws Exception {  
  42.   
  43.             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
  44.             DocumentBuilder db = dbf.newDocumentBuilder();  
  45.             Document document = db.newDocument();  
  46.             Element rootElement = document.createElement("myrows");// 这里名字随便,以外面为准,JAXB会自动替换名字的  
  47.             document.appendChild(rootElement);  
  48.   
  49.             for (Map<String, String> row : rows) {  
  50.   
  51.                 Element rowEle = document.createElement("row");  
  52.   
  53.                 Element idEle = document.createElement("id");  
  54.                 Element nameEle = document.createElement("name");  
  55.   
  56.                 Entry<String, String> entry = row.entrySet().iterator().next();// 第一个ENTRY  
  57.                 String id = entry.getKey();// ID  
  58.                 String name = entry.getValue();// NAME  
  59.   
  60.                 idEle.setTextContent(id);  
  61.                 nameEle.setTextContent(name);  
  62.                 rowEle.appendChild(idEle);  
  63.                 rowEle.appendChild(nameEle);  
  64.                 rootElement.appendChild(rowEle);  
  65.             }  
  66.             return rootElement;  
  67.         }  
  68.   
  69.         /** 
  70.          * 把XML ELEMENT转化成JAVA对象 
  71.          */  
  72.         @Override  
  73.         public List<Map<String, String>> unmarshal(Object rowsElement)  
  74.                 throws Exception {  
  75.   
  76.             if (rowsElement == null) {  
  77.                 return null;  
  78.             }  
  79.   
  80.             Element rowsEle = (Element) rowsElement;  
  81.   
  82.             NodeList rowNodes = rowsEle.getChildNodes();  
  83.             int rowCount = (rowNodes == null ? 0 : rowNodes.getLength());  
  84.             if (rowCount == 0) {  
  85.                 return null;  
  86.             }  
  87.             List<Map<String, String>> result = new ArrayList<Map<String, String>>(  
  88.                     rowCount);  
  89.   
  90.             for (int i = 0; i < rowCount; i++) {  
  91.                 Node rowNode = rowNodes.item(i);  
  92.                 if (!"row".equals(rowNode.getNodeName())) {  
  93.                     System.out.println("发现非法节点:" + rowNode.getNodeName()  
  94.                             + "忽略.");  
  95.                     continue;  
  96.                 }  
  97.                 NodeList idNameNodes = rowNode.getChildNodes();  
  98.                 int nodeSize = (idNameNodes == null ? 0 : idNameNodes  
  99.                         .getLength());  
  100.                 if (nodeSize == 0) {  
  101.                     continue;  
  102.                 }  
  103.                 Map<String, String> row = new HashMap<String, String>();  
  104.                 String id = null;  
  105.                 String name = null;  
  106.                 for (int j = 0; j < nodeSize; j++) {  
  107.                     Node node = idNameNodes.item(j);  
  108.                     String nodeName = node.getNodeName();  
  109.                     String nodeValue = node.getTextContent();  
  110.                     if ("id".equals(nodeName)) {  
  111.                         id = nodeValue;  
  112.                     } else if ("name".equals(nodeName)) {  
  113.                         name = nodeValue;  
  114.                     }  
  115.                     if (id != null && name != null) {  
  116.                         break;  
  117.                     }  
  118.                 }  
  119.   
  120.                 if (id != null) {  
  121.                     row.put(id, name);  
  122.                 } else {  
  123.                     System.out.println("未在row节点里发现id节点,忽略.");  
  124.                 }  
  125.                 result.add(row);  
  126.             }  
  127.   
  128.             return result;  
  129.         }  
  130.   
  131.     }  
  132.       
  133.     @XmlElement(name="count")  
  134.     private int count;  
  135.     @XmlElement(name="rows")  
  136.     @XmlJavaTypeAdapter(UserRowsXmlAdapter.class)  
  137.     private List<Map<String, String>> rows;  
  138.   
  139.     public int getCount() {  
  140.         return count;  
  141.     }  
  142.   
  143.     public void setCount(int count) {  
  144.         this.count = count;  
  145.     }  
  146.   
  147.     public List<Map<String, String>> getRows() {  
  148.         return rows;  
  149.     }  
  150.   
  151.     public void setRows(List<Map<String, String>> rows) {  
  152.         this.rows = rows;  
  153.     }  
  154.   
  155.     @Override  
  156.     public String toString() {  
  157.         return "User [count=" + count + ", rows=" + rows + "]";  
  158.     }  
  159.   
  160.     public static void main(String[] args) throws JAXBException {  
  161.         User u = new User();  
  162.         List<Map<String, String>> rows = new ArrayList<Map<String, String>>(2);  
  163.         Map<String, String> row = new HashMap<String, String>();  
  164.         row.put("1""土豆");// userid=1,username=土豆  
  165.         rows.add(row);  
  166.         row = new HashMap<String, String>();  
  167.         row.put("2""洋葱");// userid=2,username=洋葱  
  168.         rows.add(row);  
  169.         u.setCount(rows.size());  
  170.         u.setRows(rows);  
  171.   
  172.         JAXBContext jc = JAXBContext.newInstance(User.class);  
  173.         StringWriter writer = new StringWriter();  
  174.         jc.createMarshaller().marshal(u, writer);  
  175.         System.out.println("Marshalled xml==>");  
  176.         System.out.println(writer);  
  177.         String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"  
  178.                 + "<user><count>2</count><rows><row><id>1</id><name>土豆</name>"  
  179.                 + "</row><row><id>2</id><name>洋葱</name>"  
  180.                 + "</row></rows></user>";  
  181.   
  182.         User newu = (User) jc.createUnmarshaller().unmarshal(  
  183.                 new StringReader(xml));  
  184.         System.out.println("UnMarshalled user==>");  
  185.         System.out.println(newu);  
  186.     }  
  187.   
  188. }  


输出结果:

Java代码  收藏代码
  1. Marshalled xml==>  
  2.   
  3. <?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>  
  4.   
  5. UnMarshalled user==>  
  6.   
  7. User [count=2, rows=[{1=土豆}, {2=洋葱}]] 
原创粉丝点击