Tôi giải quyết nó bằng cách tạo ra một thực hiện Convertor, như được giải thích here. Giải pháp của tôi cho vấn đề là như sau:
Patient.java
public class Patient {
String name;
Report report;
}
Report.java
public class Report {
public String report;
}
An thực hiện một Convertor cho 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;
}
}
Ví dụ sử dụng công cụ chuyển đổi với 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);
Output
patient: Mr. Sick
patient.report: <paragraph>some text here<bold>Conclusion</bold>text...
...</paragraph><sdf>hello world</sdf>
Bạn có thể làm điều này bằng cách sử dụng thực hiện JAXB (Metro, EclipseLink MOXY, Apache JaxMe), với chú thích '@ XmlAnyElement': http://blog.bdoughan.com/2011/04/xmlanyelement-and-non-dom-properties.html –
Cảm ơn. Mặc dù tôi không sử dụng giải pháp này, nó giúp tìm ra câu trả lời. Tìm kiếm trên @XmlAnyElement kết hợp với XStream đã cho tôi đủ thông tin để giúp tôi tiếp tục. Tôi đã đăng câu trả lời cho câu hỏi này. – boes