我使用 JAXB 作为编码器。
我有一个包含字符串列表和其他属性的对象。我想将列表内容编码为单独的标签。
我的代码是List<String> items
。如果我将字符串“apple”、“banana”、“orange”添加到列表中,我希望在编码时生成的 xml 为:
<items>
<apple/>
<banana/>
<orange/>
</items>
这可行吗?或者,要获得该结果,我该如何更改对象?
(抱歉格式错误,我无法做得更好)
最佳答案
我的建议
我的建议是不要这样做。相反,让您的 XML 消息如下(这将使每个人都更容易处理您的 XML):
<items>
<item>apple</item>
<item>banana</item>
<item>orange</item>
</items>
如何做到这一点
好吧,你决定不听从我的建议:)。以下是您可以如何做到的:
创建
XmlAdapter
可以转换String
到org.w3c.dom.Element
的实例其名称等于String
.import javax.xml.bind.annotation.adapters.XmlAdapter; import javax.xml.parsers.*; import org.w3c.dom.*; public class StringAdapter extends XmlAdapter<Object, String> { private Document document; @Override public String unmarshal(Object v) throws Exception { Element element = (Element) v; return element.getTagName(); } @Override public Object marshal(String v) throws Exception { return getDocument().createElement(v); } private Document getDocument() throws Exception { if(null == document) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); document = db.newDocument(); } return document; } }
注释您的
List<String>
字段/属性@XmlJavaTypeAdapter
指向你的XmlAdapter
和@XmlAnyElement
注释。import java.util.*; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; @XmlRootElement public class Items { private List<String> items = new ArrayList<String>(); @XmlAnyElement @XmlJavaTypeAdapter(StringAdapter.class) public List<String> getItems() { return items; } }
要提高性能,请确保您的
XmlAdapter
持有Document
的实例并设置XMLAdapter
关于Marshaller
使其成为有状态的,以避免每次XmlAdapter
时都需要重新创建它被调用。import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Items.class); Items items = new Items(); items.getItems().add("apple"); items.getItems().add("banana"); items.getItems().add("orange"); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setAdapter(new StringAdapter()); marshaller.marshal(items, System.out); } }
关于java - JaxB 如何将列表的内容编码为单独的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21312323/