[英]How to partially marshall/unmarshall an object?
I have a class A with attributes B b and C c that I want to marshall and unmarshall in a way that in c instead of having an java object graph, I want a string representation of the XML fragment, ie
@XmlRootElement(namespace="test")
public class A {
B b;
C c;
//omitting getters and setters
}
public class C {
String xmlFragment;
//This string will contain the following:
//"<d>d</d><e><f>f1</f><f>f2</></e>
}
並且產生/產生的 XML 看起來像
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<A xmlns="test">
<B>some B content that is mapped to java objects</B>
<C>
<d>d</d><e><f>f1</f><f>f2</></e>
</C>
</A>
我如何使用 JAXB 來實現這一點?
JAXB 不會那么做。 它可以做的是處理一個org.w3c.dom.Element
,並將其序列化為 XML,即
@XmlRootElement(namespace="test")
public class A {
B b;
@XmlAnyElement Element c;
}
因此,您需要將 XML 片段解析為一個Element
(例如使用DocumentBuilderFactory
),然后它就會起作用。
我想你可以在運行時解析Element
,但要非常小心性能損失:
@XmlRootElement(namespace="test")
public class A {
B b;
String xmlFragment;
@XmlAnyElement
public Element getXmlFragment() {
InputSource source = new InputSource(new StringReader(xmlFragment));
Document doc = DocumentBuilderFactory.newInstance().parse(source);
return doc.getDocumentElement();
}
}
您需要對 C 類型使用 XmlAdapter 實現。
@XmlRootElement(namespace="test")
public class A {
B b;
@XmlJavaTypeAdapter(MyAdapter.class)
C c;
//omitting getters and setters
}
class MyAdapter extends XmlAdapter<String,C> {
public C unmarshal(String s) {
// custom unmarshalling
return null;
}
public String marshal(C c) {
// custom marshalling
return "blah";
}
}
希望這就是你所追求的。
問候優素福
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.