将具有不同rootelement名称的两个xmls映射到同一个java对象

时间:2011-10-19 21:57:15

标签: java xml jaxb

我有

xml1:
<abc><name>hello</name></abc>

xml2
<xyz><name>hello</name></xyz>

I have one java class. 

@XmlRootElement(name="abc") (this 
public class Foo{
   @XmlElement
   String name;
}

我不想要另一个类,但想用Foo类本身来容纳xml2。 我可以在编组前/解组前拦截或修改它。

谢谢!

}

2 个答案:

答案 0 :(得分:1)

根据“我不想要其他课程”的具体含义,也许这对您有用:

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import java.io.StringReader;

public class JaxbBindTwoRootElementsToSameClass {
    public static void main(String[] args) throws Exception {
        String xml1 = "<abc><name>hello</name></abc>";
        String xml2 = "<xyz><name>hello</name></xyz>";
        Unmarshaller unmarshaller = JAXBContext.newInstance(Foo.class).createUnmarshaller();
        Object o1 = unmarshaller.unmarshal(new StringReader(xml1));
        Object o2 = unmarshaller.unmarshal(new StringReader(xml2));
        System.out.println(o1);
        System.out.println(o2);
    }

    @XmlSeeAlso({Foo.Foo_1.class, Foo.Foo_2.class})
    static class Foo {
        @XmlRootElement(name = "abc")
        static class Foo_1 extends Foo {}

        @XmlRootElement(name = "xyz")
        static class Foo_2 extends Foo {}

        @XmlElement
        String name;

        @Override
        public String toString() {
            return "Foo{name='" + name + '\'' + '}';
        }
    }
}

输出:

Foo{name='hello'}
Foo{name='hello'}

它几乎完全按照您通常的方式使用JAXB。这只是一个有点不同寻常的阶级组织。您甚至只需在创建时将Foo.class传递给JAXBContext。不需要修改JAXB内部构件。

答案 1 :(得分:0)

<强>解组

您可以使用带有类参数的unmarshal方法。指定类时,JAXB实现不需要使用root元素来确定要解组的类。

<强>编组

编组时,可以将根对象包装在JAXBElement中以提供根元素信息。