当元素具有值和子元素时,将转换器与 xstream 一起使用
我有一个 XML 字符串,如下所示:
<e1 atr1="3" atr2="asdf">
<e1b atr3="3" atr4="asdf">
<e1c atr5="3" atr6="asdf"/>
TestValue1
</e1b>
<e1b atr3="3" atr4="asdf">
<e1c atr5="3" atr6="asdf"/>
TestValue2
</e1b>
</e1>
它与我过去解析的其他 XML 不同,因为 e1b 元素具有值 TestValue1
和 TestValue2
以及子元素元素(e1c
)。
如果一个元素同时具有属性和值,则必须为 xstream 创建一个自定义转换器才能解析它。我的尝试如下,但因为 e1b 元素具有属性、子元素和值,所以我不确定如何处理它。在我的转换器中,我删除了对 e1c
子元素的所有引用。我需要向转换器添加什么才能使其正确处理 e1c
元素?现在,当我执行 xstream.fromXML()
时,e1c
值不会被填充。
public class e1Converter implements Converter {
@SuppressWarnings("rawtypes")
public boolean canConvert(Class clazz) {
return e1b.class == clazz;
}
public void marshal(Object object, HierarchicalStreamWriter hsw,
MarshallingContext mc) {
e1b e = (e1b) object;
hsw.addAttribute("atr3", e.getAtr3());
hsw.addAttribute("atr4", e.getAtr4());
hsw.setValue(e.getE1bValue());
}
public Object unmarshal(HierarchicalStreamReader hsr,
UnmarshallingContext uc) {
e1b e = new e1b();
e.setAtr3(hsr.getAttribute("atr3"));
e.setAtr4(hsr.getAttribute("atr4"));
e.setE1bValue(hsr.getValue());
return e;
}
}
I have a string of XML that looks like this:
<e1 atr1="3" atr2="asdf">
<e1b atr3="3" atr4="asdf">
<e1c atr5="3" atr6="asdf"/>
TestValue1
</e1b>
<e1b atr3="3" atr4="asdf">
<e1c atr5="3" atr6="asdf"/>
TestValue2
</e1b>
</e1>
It is different than other XML I have parsed in the past because the e1b elements have values TestValue1
and TestValue2
as well as child elements (e1c
).
If an element has both attributes and a value, you have to create a custom converter for xstream to be able to parse it. My attempt at that is below, but because the e1b element has attributes, child elements, AND a value, I'm not sure how to handle it. In my converter, I have left off all references to the e1c
child element. What do I need to add to the converter to allow it to handle the e1c
element correctly? Right now, e1c
values are not getting populated when I do a xstream.fromXML()
.
public class e1Converter implements Converter {
@SuppressWarnings("rawtypes")
public boolean canConvert(Class clazz) {
return e1b.class == clazz;
}
public void marshal(Object object, HierarchicalStreamWriter hsw,
MarshallingContext mc) {
e1b e = (e1b) object;
hsw.addAttribute("atr3", e.getAtr3());
hsw.addAttribute("atr4", e.getAtr4());
hsw.setValue(e.getE1bValue());
}
public Object unmarshal(HierarchicalStreamReader hsr,
UnmarshallingContext uc) {
e1b e = new e1b();
e.setAtr3(hsr.getAttribute("atr3"));
e.setAtr4(hsr.getAttribute("atr4"));
e.setE1bValue(hsr.getValue());
return e;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据 Jörg 在 xstream 邮件列表上的说法:
According to Jörg on the xstream mailing list: