XML解析为对象

jaxb解析xml为对象例子

文章分类:Java编程

通过jaxb方式把xml文件映射成bean对象。

1、新建java工程或者web工程都可以。
2、通过精简必须导入jar包
         activation.jar
        jaxb-api-2.0.jar
        jaxb-impl-2.0.1.jar
        jsr173_api-1.0.jar
3、 新建xml文件
    <?xml version="1.0" encoding="UTF-8"?>
    < root>

< template
   start="true"
   ip="127.0.0.1"
   port="3344"
   server="server"
/>
<template ... ... />
    </root>

4、新建bean对象,xml的映射文件。
Vo.java 如下
  
Java代码 复制代码
  1. import javax.xml.bind.annotation.XmlAccessType;   
  2. import javax.xml.bind.annotation.XmlAccessorType;   
  3. import javax.xml.bind.annotation.XmlAttribute;   
  4. import javax.xml.bind.annotation.XmlRootElement;   
  5. import javax.xml.bind.annotation.XmlType;   
  6.   
  7. @XmlAccessorType(XmlAccessType.FIELD)   
  8. @XmlType(name = "", propOrder = {   
  9. })   
  10. @XmlRootElement(name = "[color=red]template[/color]")   
  11. public class Vo {   
  12.   
  13.     @XmlAttribute  
  14.     private String start;   
  15.     @XmlAttribute  
  16.     private String ip;   
  17.     @XmlAttribute  
  18.     private String port;   
  19.     @XmlAttribute  
  20.     private String server;   
  21.        
  22.        
  23.     public String getStart() {   
  24.         return start;   
  25.     }   
  26.     public void setStart(String start) {   
  27.         this.start = start;   
  28.     }   
  29.     public String getIp() {   
  30.         return ip;   
  31.     }   
  32.     public void setIp(String ip) {   
  33.         this.ip = ip;   
  34.     }   
  35.     public String getPort() {   
  36.         return port;   
  37.     }   
  38.     public void setPort(String port) {   
  39.         this.port = port;   
  40.     }   
  41.     public String getServer() {   
  42.         return server;   
  43.     }   
  44.     public void setServer(String server) {   
  45.         this.server = server;   
  46.     }   
  47. }   
  48.      
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
})
@XmlRootElement(name = "[color=red]template[/color]")
public class Vo {

	@XmlAttribute
	private String start;
	@XmlAttribute
	private String ip;
	@XmlAttribute
	private String port;
	@XmlAttribute
	private String server;
	
	
	public String getStart() {
		return start;
	}
	public void setStart(String start) {
		this.start = start;
	}
	public String getIp() {
		return ip;
	}
	public void setIp(String ip) {
		this.ip = ip;
	}
	public String getPort() {
		return port;
	}
	public void setPort(String port) {
		this.port = port;
	}
	public String getServer() {
		return server;
	}
	public void setServer(String server) {
		this.server = server;
	}
}
   

该文件对应xml文件中 循环节点 template 元素

Root.java 文件如下
Java代码 复制代码
  1. import java.util.ArrayList;   
  2. import java.util.List;   
  3.   
  4. import javax.xml.bind.annotation.XmlAccessType;   
  5. import javax.xml.bind.annotation.XmlAccessorType;   
  6. import javax.xml.bind.annotation.XmlRootElement;   
  7. import javax.xml.bind.annotation.XmlType;   
  8.   
  9. @XmlAccessorType(XmlAccessType.FIELD)   
  10. @XmlType(name = "", propOrder = {   
  11. })   
  12. @XmlRootElement(name = "[color=blue]root[/color]")   
  13. public class Root {   
  14.        
  15.     protected List<Vo> [color=red]template[/color];   
  16.        
  17.     public List<Vo> getTemplateList() {   
  18.         if (template == null) {   
  19.             template = new ArrayList<Vo>();   
  20.         }   
  21.         return this.template;   
  22.     }   
  23. }  
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
})
@XmlRootElement(name = "[color=blue]root[/color]")
public class Root {
	
	protected List<Vo> [color=red]template[/color];
	
	public List<Vo> getTemplateList() {
        if (template == null) {
        	template = new ArrayList<Vo>();
        }
        return this.template;
    }
}


注意bean对象与xml映射的关系。

5、 解析xml为bean类
Java代码 复制代码
  1. public static void gernateConfig() throws Exception{   
  2.         StringBuffer buffer  = null;   
  3.         JAXBContext jaxbContext;   
  4.         try {   
  5.                            //读入xml文件流   
  6.                            InputStream is = Excecute.class.getResourceAsStream(“/conf/config.xml”);   
  7.             BufferedReader in = new BufferedReader(new InputStreamReader(is));   
  8.             buffer = new StringBuffer();   
  9.             String line = "";   
  10.             while ((line = in.readLine()) != null) {   
  11.                 buffer.append(line);   
  12.             }   
  13.                
  14.             //加载映射bean类   
  15.             jaxbContext = JAXBContext.newInstance(Root.class);   
  16.                            //创建解析   
  17.             Unmarshaller um = jaxbContext.createUnmarshaller();   
  18.             StreamSource streamSource = new StreamSource(new StringReader(buffer.toString()));   
  19.             Root root = (Root) um.unmarshal(streamSource);    
  20.         } catch (Exception e) {   
  21.             e.printStackTrace();   
  22.             throw new Exception(e.getMessage());   
  23.         }   
  24.     }  
public static void gernateConfig() throws Exception{
		StringBuffer buffer  = null;
		JAXBContext jaxbContext;
		try {
                           //读入xml文件流
                           InputStream is = Excecute.class.getResourceAsStream(“/conf/config.xml”);
			BufferedReader in = new BufferedReader(new InputStreamReader(is));
			buffer = new StringBuffer();
			String line = "";
			while ((line = in.readLine()) != null) {
				buffer.append(line);
			}
			
			//加载映射bean类
			jaxbContext = JAXBContext.newInstance(Root.class);
                           //创建解析
			Unmarshaller um = jaxbContext.createUnmarshaller();
			StreamSource streamSource = new StreamSource(new StringReader(buffer.toString()));
			Root root = (Root) um.unmarshal(streamSource); 
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e.getMessage());
		}
	}


6、 把bean对象生成xml字符串方法
Java代码 复制代码
  1. public static String gernateConfigXml(Root root) throws Exception {   
  2.         if (root != null) {   
  3.             try {   
  4.                 JAXBContext context = JAXBContext.newInstance(Root.class);   
  5.                 Marshaller m = context.createMarshaller();   
  6.                 m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);   
  7.                 Writer writer = new StringWriter();   
  8.                 m.marshal(root, writer);   
  9.                 try {   
  10.                     String xml = writer.toString();   
  11.                     writer.flush();   
  12.                     writer.close();   
  13.                     return xml;   
  14.                 } catch (IOException e) {   
  15.                     return "";   
  16.                 }   
  17.             } catch (Exception e) {   
  18.                 throw new Exception("失败!");   
  19.             }   
  20.         } else {   
  21.             return null;   
  22.         }   
  23.     }  
public static String gernateConfigXml(Root root) throws Exception {
		if (root != null) {
			try {
				JAXBContext context = JAXBContext.newInstance(Root.class);
				Marshaller m = context.createMarshaller();
				m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
				Writer writer = new StringWriter();
				m.marshal(root, writer);
				try {
					String xml = writer.toString();
					writer.flush();
					writer.close();
					return xml;
				} catch (IOException e) {
					return "";
				}
			} catch (Exception e) {
				throw new Exception("失败!");
			}
		} else {
			return null;
		}
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值