我解決它通過創建一個轉換器實現,如解釋here。我對問題的解決方案如下:
Patient.java
public class Patient {
String name;
Report report;
}
Report.java
public class Report {
public String report;
}
爲XStream的
一個轉換器的一個實施
public class ReportConverter implements Converter {
@Override
public boolean canConvert(Class classs) {
System.out.println("canConvert: " + classs.getName());
return classs.equals(Report.class);
}
@Override
public void marshal(Object value, HierarchicalStreamWriter writer,
MarshallingContext context) {
// not used in this example
}
// goes recursive through all the nodes in <report>
String getNodeAsText(HierarchicalStreamReader reader) {
String result;
result = "<" + reader.getNodeName() + ">" + reader.getValue();
while (reader.hasMoreChildren()) {
reader.moveDown();
result += getNodeAsText(reader);
reader.moveUp();
result += reader.getValue();
}
result += "</" + reader.getNodeName() + ">";
return result;
}
@Override
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
Report xReport = new Report();
xReport.report = reader.getValue();
while (reader.hasMoreChildren()) {
reader.moveDown();
xReport.report += getNodeAsText(reader);
reader.moveUp();
xReport.report += reader.getValue();
}
return xReport;
}
}
實施例使用的帶XStream的轉換器
XStream xStream = new XStream();
xStream.registerConverter(new ReportConverter());
xStream.alias("patient", Patient.class);
xStream.alias("report", Report.class);
String xml = "<patient><name>Mr. Sick</name><report><paragraph>" +
"some text here<bold>Conclusion</bold>text...</paragraph>" +
"<sdf>hello world</sdf></report></patient>";
Patient patient = (Patient)xStream.fromXML(xml);
System.out.println("patient.name: " + patient.name);
System.out.println("patient.report: " + patient.report.report);
輸出
patient: Mr. Sick
patient.report: <paragraph>some text here<bold>Conclusion</bold>text...
...</paragraph><sdf>hello world</sdf>
你可以使用JAXB實現(新城的EclipseLink莫西,阿帕奇這樣做JaxMe),與'@ XmlAnyElement'註釋:http://blog.bdoughan.com/2011/04/xmlanyelement-and-non-dom-properties.html –
感謝。儘管我沒有使用這個解決方案,但它有助於找到答案。在XStream中搜索@XmlAnyElement,給了我足夠的信息讓我重新開始。我發佈了我對這個問題的回答。 – boes