Xml与实体类的相互转化

public class XmlUtil
{
	public static object Deserialize(Type type, string xml)
	{
		using(StringReader sr = new StringReader(xml))
		{
			XmlSerializer xmldes = new XmlSerializer(Type);
			return xmldes.Deserialize(sr);
		}
	}
	public static object Deserialize(Type type, Stream xml)
	{
		XmlSerializer xmldes = new XmlSerializer(Type);
		return xmldes.Deserialize(xml);
	}

	public static string Serialize(Type type, object obj)
	{
		MemoryStream Stream = new MemoryStream();
		XmlSerializer xml = new XmlSerializer(Type);
		xml.Serialize(Stream, obj);
		Stream.Position = 0;
		StringReader sr = new StringReader(Stream);
		string str = sr.ReadToEnd();
		sr.Dispose();
		Stream.Dispose();
		return str;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中可以使用JAXB(Java Architecture for XML Binding)库将实体类换为XML,JAXB提供了将Java对象和XML文档相互换的能力。 以下是一个示例代码,将Book类换为XML格式: ```java import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.annotation.XmlRootElement; import java.io.StringWriter; @XmlRootElement public class Book { private String title; private String author; private int year; private float price; public Book() {} public Book(String title, String author, int year, float price) { this.title = title; this.author = author; this.year = year; this.price = price; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public static void main(String[] args) throws Exception { Book book = new Book("Java Programming", "John Smith", 2021, 29.99f); JAXBContext jaxbContext = JAXBContext.newInstance(Book.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter writer = new StringWriter(); marshaller.marshal(book, writer); System.out.println(writer.toString()); } } ``` 输出结果为: ```xml <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <book> <author>John Smith</author> <price>29.99</price> <title>Java Programming</title> <year>2021</year> </book> ``` 在上面的代码中,我们使用了JAXBContext.newInstance()方法来创建一个JAXBContext对象,然后使用createMarshaller()方法创建Marshaller对象,最后调用marshal()方法将Java对象换为XML格式,并将结果输出到字符串中。在Book类上使用了@XmlRootElement注解,这个注解用来指定生成XML文件的根元素名称。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值