刚刚接手的一个项目,接到一个对接用户数据的需求,对方使用的是xml格式来传输文件,特此记下解析该类文件的方法
public interface XmlResolver<T> {
XStream builder();
default T parse(String xml){
return (T) builder().fromXML(xml);
}
default T resolver(String xml){
return parse(xml);
}
}
//测试类
public class TestMain {
private String name;
private String address;
private List<TestPerson> personList;
public static void main(String[] args) {
XmlResolver<TestMain> testMainXmlResolver = () -> {
{
XStream xStream = new XStream();
xStream.alias("GetInvoiceResult", TestMain.class);
xStream.alias("ItemRecord", TestPerson.class);
return xStream;
}
};
String xml = "<GetInvoiceResult>
" +
" <name>string</name>
" +
" <address>string</address>
" +
" <personList>
" +
" <ItemRecord>
" +
" <name>string</name>
" +
" <age>string</age>
" +
" </ItemRecord>
" +
" <ItemRecord>
" +
" <name>string</name>
" +
" <age>string</age>
" +
" </ItemRecord>
" +
" </personList>
" +
" </GetInvoiceResult>
"
;
TestMain testMain = testMainXmlResolver.parse(xml);
System.out.println(testMain);
}
}