I have started using the xstream library to convert from Java code to XML. My model java class is simple and given below:
我已经开始使用xstream库将Java代码转换为XML。我的模型java类很简单,如下所示:
class Person {
String firstname;
String lastname;
String age;
public Person(String first, String last,String age) {
firstname = first;
lastname = last;
this.age = age;
}
}
So using simple xstream API I am getting the output of the toXML
method as below:
所以使用简单的xstream API我得到了toXML方法的输出如下:
<Person>
<firstname>David</firstname>
<lastname>Goswami</lastname>
<age>34</age>
</Person>
However, I want to tweak the output and get the string age as an attribute of the field firstname. In essence, I am expecting the xml output as below:
但是,我想调整输出并将字符串age作为字段firstname的属性。本质上,我期待xml输出如下:
<Person>
<firstname age="34">David</firstname>
<lastname>Goswami</lastname>
</Person>
Any help on how to do this would be highly appreciated.
任何有关如何做到这一点的帮助将受到高度赞赏。
3 个解决方案
#1
0
You can use XStream.useAttributeFor()
to declare a property to be serialized as an attribute:
您可以使用XStream.useAttributeFor()声明要作为属性序列化的属性:
xstream.useAttributeFor(Person.class, "age");
#2
0
@XStreamAsAttribute
String age;
#3
0
You can use user-defined Converter, good example with the similar problem is there: http://www.coderanch.com/t/426981/XML/XStream-variable-as-attribute-another
您可以使用用户定义的转换器,类似问题的好例子是:http://www.coderanch.com/t/426981/XML/XStream-variable-as-attribute-another
#1
0
You can use XStream.useAttributeFor()
to declare a property to be serialized as an attribute:
您可以使用XStream.useAttributeFor()声明要作为属性序列化的属性:
xstream.useAttributeFor(Person.class, "age");
#2
0
@XStreamAsAttribute
String age;
#3
0
You can use user-defined Converter, good example with the similar problem is there: http://www.coderanch.com/t/426981/XML/XStream-variable-as-attribute-another
您可以使用用户定义的转换器,类似问题的好例子是:http://www.coderanch.com/t/426981/XML/XStream-variable-as-attribute-another