Vik*_*bin 7 java xml parsing xstream
我正在使用XStream,我有一个XML示例:
<person>
<firstname>Joe</firstname>
<lastname>Walnes</lastname>
<phone value="1234-456" />
<fax value="9999-999" />
</person>
Run Code Online (Sandbox Code Playgroud)
我想把它映射到课堂上
public class Person {
private String firstname;
private String lastname;
private String phone;
private String fax;
}
Run Code Online (Sandbox Code Playgroud)
因此,我们的想法是将嵌套元素的属性映射到当前对象.我试图找到任何即用型转换器但没有成功.我相信通过实施新的转换器是可能的,但也许有人已经这样做了.或者有一个我没有找到的解决方案.
更新:
我想要实现的想法是省略不必要的创建和映射实体.我根本不需要电话和传真实体,我只需要在我的模型中使用它们的属性.我试图解析的XML模式对我来说是第三方,我无法改变它.
我不知道一个即将使用的转换器会做到这一点,但写一个很简单
import com.thoughtworks.xstream.converters.*;
import com.thoughtworks.xstream.io.*;
public class ValueAttributeConverter implements Converter {
public boolean canConvert(Class cls) {
return (cls == String.class);
}
public void marshal(Object source, HierarchicalStreamWriter w, MarshallingContext ctx) {
w.addAttribute("value", (String)source);
}
public Object unmarshal(HierarchicalStreamReader r, UnmarshallingContext ctx) {
return r.getAttribute("value");
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用注释将转换器附加到相关字段
import com.thoughtworks.xstream.annotations.*;
@XStreamAlias("person")
public class Person {
private String firstname;
private String lastname;
@XStreamConverter(ValueAttributeConverter.class)
private String phone;
@XStreamConverter(ValueAttributeConverter.class)
private String fax;
// add appropriate constructor(s)
/** For testing purposes - not required by XStream itself */
public String toString() {
return "fn: " + firstname + ", ln: " + lastname +
", p: " + phone + ", f: " + fax;
}
}
Run Code Online (Sandbox Code Playgroud)
要使这项工作,您需要做的就是指示XStream读取注释:
XStream xs = new XStream();
xs.processAnnotations(Person.class);
Person p = (Person)xs.fromXML(
"<person>\n" +
" <firstname>Joe</firstname>\n" +
" <lastname>Walnes</lastname>\n" +
" <phone value='1234-456' />\n" +
" <fax value='9999-999' />\n" +
"</person>");
System.out.println(p);
// prints fn: Joe, ln: Walnes, p: 1234-456, f: 9999-999
Run Code Online (Sandbox Code Playgroud)