XStream处理既有属性又有值的xml节点

前端之家收集整理的这篇文章主要介绍了XStream处理既有属性又有值的xml节点前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

XML文件如下:

<Order>
  <Status Id="123">abc</Status>
</Order>
Status节点就是一个既有属性又有值的节点。


Maven配置:

<dependency>
	<groupId>com.thoughtworks.xstream</groupId>
	<artifactId>xstream</artifactId>
	<version>1.4.7</version>
</dependency>
测试:
package org.xstream;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class AppTest {
	static String xml = "<Order><Status Id=\"123\">abc</Status></Order>";

	public static void main(String[] args) {
		XStream xstream = new XStream();
		xstream.alias("Order",Order.class);
		xstream.registerConverter(new Converter() {

			@Override
			public boolean canConvert(Class type) {
				return type.equals(Status.class);
			}

			@Override
			public Object unmarshal(HierarchicalStreamReader reader,UnmarshallingContext context) {
				Status s = new Status();
				s.setId(reader.getAttribute("Id"));
				s.setContent(reader.getValue());
				return s;
			}

			@Override
			public void marshal(Object source,HierarchicalStreamWriter writer,MarshallingContext context) {
				Status status = (Status) source;
				writer.addAttribute("Id",status.getId());
				writer.setValue(status.getContent());
			}
		});
		Order order = (Order) xstream.fromXML(xml);
		System.out.println("-----反序列化-----");
		System.out.println(order);
		
		System.out.println("----序列化-----");
		System.out.println(xstream.toXML(order));
	}
}

class Order {
	private Status Status;

	public Status getStatus() {
		return Status;
	}

	public void setStatus(Status status) {
		Status = status;
	}

	@Override
	public String toString() {
		return "Order [Status=" + Status + "]";
	}

}

class Status {
	private String Id;
	private String content;

	public String getId() {
		return Id;
	}

	public void setId(String id) {
		Id = id;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	@Override
	public String toString() {
		return "Status [Id=" + Id + ",content=" + content + "]";
	}

}

输出结果:

-----反序列化-----
Order [Status=Status [Id=123,content=abc]]
----序列化-----
<Order>
  <Status Id="123">abc</Status>
</Order>
原文链接:https://www.f2er.com/xml/295940.html

猜你在找的XML相关文章