java XStream:具有属性和文本节点的节点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1726863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XStream : node with attributes and text node?
提问by subb
I would like to serialize an object to an XML of this form with XStream.
我想使用 XStream 将对象序列化为这种形式的 XML。
<node att="value">text</node>
The value of the node (text) is a field on the serialized object, as well as the attattribute. Is this possible without writing a converter for this object?
节点 ( text)的值是序列化对象上的一个字段,以及att属性。如果不为此对象编写转换器,这可能吗?
Thanks!
谢谢!
采纳答案by Kiru
write a convertor, it should be something similar to the code snippet
写一个转换器,它应该类似于代码片段
class FieldDtoConvertor implements Converter {
@SuppressWarnings("unchecked")
public boolean canConvert(final Class clazz) {
return clazz.equals(FieldDto.class);
}
public void marshal(final Object value,
final HierarchicalStreamWriter writer,
final MarshallingContext context) {
final FieldDto fieldDto = (FieldDto) value;
writer.addAttribute(fieldDto.getAttributeName(), fieldDto.getAttributeValue());
}
}
And while using XStream,register the convertor
并在使用 XStream 时,注册转换器
final XStream stream = new XStream(new DomDriver());
stream.registerConverter(new FieldDtoConvertor());
回答by mantrid
you can use a predefined Converter.
您可以使用预定义的转换器。
@XStreamAlias("node")
@XStreamConverter(value=ToAttributedValueConverter.class, strings={"text"})
class Node {
private String att;
private String text;
}
XStream Annotations Tutorialalso says that for attattribute:
XStream Annotations Tutorial也说对于att属性:
Note, that no XStreamAsAttribute annotations were necessary. The converter assumes it implicitly.
请注意,不需要 XStreamAsAttribute 注释。转换器隐式地假定它。
回答by bdoughan
This is much easier in JAXB
这在 JAXB 中要容易得多
@XmlRootElement
public class Node {
@XmlAttribute
String att;
@XmlValue
String value;
}
回答by Thomas
Just another way of doing it:
只是另一种方式:
@XStreamAlias("My")
private static class My {
private String field;
}
XStream xStream = new XStream();
xStream.autodetectAnnotations(true);
xStream.useAttributeFor(My.class, "field");

