动态根元素JAXB?

问题描述 投票:3回答:1

我正在尝试与第三方系统集成,并且根据对象的类型,返回的XML文档的根元素会发生变化。我正在使用JAXB库进行编组/解组。

Root1:

<?xml version="1.0" encoding="UTF-8"?>
<root1 id='1'>
   <MOBILE>9831138683</MOBILE>
   <A>1</A>
   <B>2</B>
</root1>

Root2:

<?xml version="1.0" encoding="UTF-8"?>
<root2 id='3'>
   <MOBILE>9831138683</MOBILE>
   <specific-attr1>1</specific-attr1>
   <specific-attr2>2</specific-attr2>
</root2>

我正在使用所有不同的XML将它们映射到通用对象

 @XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "ROW")
public class Row {

    @XmlAttribute
    private int id;
    @XmlElement(name = "MOBILE")
    private int mobileNo;

    @XmlMixed
    @XmlAnyElement
    @XmlJavaTypeAdapter(MyMapAdapter.class)
    private Map<String, String> otherElements;
}

将未知值转换为映射的适配器

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.HashMap;
import java.util.Map;

public class MyMapAdapter extends XmlAdapter<Element, Map<String, String>> {

    private Map<String, String> hashMap = new HashMap<>();

    @Override
    public Element marshal(Map<String, String> map) throws Exception {
        // expensive, but keeps the example simpler
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

        Element root = document.createElement("dynamic-elements");

        for(Map.Entry<String, String> entry : map.entrySet()) {
            Element element = document.createElement(entry.getKey());
            element.setTextContent(entry.getValue());
            root.appendChild(element);

        }

        return root;
    }


    @Override
    public Map<String, String> unmarshal(Element element) {
        String tagName = element.getTagName();
        String elementValue = element.getChildNodes().item(0).getNodeValue();
        hashMap.put(tagName, elementValue);

        return hashMap;
    }
}

这会将id和手机号码放在字段中,其余的<]。如上例所示,如果根元素固定为ROW,则此方法有效。

在每个XML中

如何使这项工作使

根元素将有所不同

?一种可能在解组时不了解根元素的方法?我正在尝试与第三方系统集成,并且根据对象的类型,返回的XML文档的根元素会发生变化。我正在使用JAXB库进行编组/解组。 ...
java xml xsd jaxb marshalling
1个回答
0
投票
恕我直言,这是一个错误的决定。代替创建变量(“动态”)根元素,您应该在同一元素中添加名称属性以区分XML文件。例如:
© www.soinside.com 2019 - 2024. All rights reserved.