我有这个课程
public class EventXML{
private String name;
private String ip;
private Date date;
private String dateFormat;
private String eventName;
}
使用此功能:
public String toXML(){
String x;
XStream xs = new XStream();
x = xs.toXML(this);
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+x;
}
我得到了这个结果:
<?xml version="1.0" encoding="UTF-8"?>
<EventXML>
<name>SuperFarmer</name>
<ip>IPPPPPPP</ip>
<myData>2018-05-15 12:48:05.343 UTC</myData>
<dateFormat>HH:mm:ss dd/MM/yyyy</dateFormat>
<eventName>CLICCA</eventName>
</EventXML>
但我希望像这样的XML:
<?xml version="1.0" encoding="UTF-8"?>
<EventXML>
<name>SuperFarmer</name>
<ip>IPPPPPPP</ip>
<myData dateFormat="HH:mm:ss dd/MM/yyyy">12:48:05 15/05/2018</myData>
<eventName>CLICCA</eventName>
</EventXML>
你可以给我一些提示来实现我的目标吗?
答案 0 :(得分:0)
我能够通过对EventXML
类进行一些更改来达到所需的xml outupt。我创建了一个包含<myData>
元素和属性的内部类:
public class EventXML
{
public String name;
public String ip;
public MyData myData = new MyData();
public String eventName;
public static class MyData {
public Date date;
public String dateFormat;
}
}
现在在序列化方法中,我们告诉xstream如何将MyData
序列化为xml元素,并告诉xstream如何转换日期字段:
ToAttributedValueConverter
接受一个类(第一个arg)和字段名称(last arg),命名字段将用作元素的值,该类的所有其他字段将用作属性
DateConverter
转换Date
类型的字段,我将其dateFormat
作为参数。
它的外观如下:
public String toXML() {
String x;
XStream xs = new XStream();
// the following tell XStream how to craete myData element:
// the last arg is the field to be used as element value and all other fields are attributes
xs.registerConverter(new ToAttributedValueConverter(MyData.class, xs.getMapper(), xs.getReflectionProvider(),
xs.getConverterLookup(), "date"));
// register date converter according to dateFormat field
xs.registerConverter(new DateConverter(myData.dateFormat, new String[]{}));
x = xs.toXML(this);
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+x;
}
答案 1 :(得分:0)
如果您使用 Xstream 1.14.x ,请使用注释。
EventXML 对象应如下所示:
public class EventXML {
public String name;
public String ip;
@XStreamAlias("myData")
public MyData myData = new MyData();
public String eventName;
@XStreamConverter(value=ToAttributedValueConverter.class, strings={"date"})
public static class MyData {
public Date date;
@XStreamAsAttribute
public String dateFormat;
}
}
Maven依赖(如果你使用maven):
<!-- https://mvnrepository.com/artifact/com.thoughtworks.xstream/xstream -->
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.10</version>
</dependency>
你的toXml方法看起来应该是这样的(使用processAnnotations):
public String toXml() {
XStream xstream = new XStream();
// Note the processAnnotations:
xstream.processAnnotations(EventXML.class);
String x = xstream.toXML(this);
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + x;
}