JAXB 解组在运行时选择根名称
JAXB unmarshal choose root name at runtime
我有几个 xml 文件,其中包含备用根元素:
<ulti86>,
<ulti75>,
<ulti99>....
否则xml结构相同
我想在同一个 pojo 中解组这些文件。
我看到可以在运行时使用
更改编组操作中的元素名称
JAXBElement and Qname (like : JAXBElement<Customer> jaxbElement =
new JAXBElement<Customer>(new QName(null, "customer"), Customer.class, customer);)
是否可以在解组时指示运行时根元素的名称?
终极 class :
@XmlRootElement
public class Ulti {
....
}
解组方法:
JAXBContext jaxbContext = JAXBContext.newInstance(Ulti.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
File xmlFile = new File(getFullFileName());
Ulti icc = (Ulti) unmarshaller.unmarshal(xmlFile);
使用 JAXB
class 根元素的名称应该是无关紧要的,您可以更改它并且解组仍然会成功。
示例输入 xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<point>
<x>1</x>
<y>2</y>
</point>
解组代码:
Point p = JAXB.unmarshal(new File("p.xml"), Point.class);
System.out.println(p); // Output: java.awt.Point[x=1,y=2]
现在,如果您再次将根元素更改为 "<p2oint>"
和 运行,您将得到相同的结果,没有任何错误。
您可以在 Unmarshaller
上使用其中一种采用 Class
参数的 unmarshal
方法来获得您正在寻找的行为。通过告诉 JAXB 您要解组的 Class
是什么类型,它不需要通过根元素自己找出一个。
StreamSource xmlSource = new StreamSource(getFullFileName());
JAXBElement<Ulti> jaxbElement = unmarshaller.unmarshal(xmlSource, Ulti.class);
Ulti icc = jaxbElement.getValue();
注:
使用 Unmarshaller.unmarshal(Source, Class)
优于 JAXB.unmarshal(File, Class)
的优势在于通过创建可重复使用的 JAXBContext
仅处理一次元数据的性能优势。
我有几个 xml 文件,其中包含备用根元素:
<ulti86>,
<ulti75>,
<ulti99>....
否则xml结构相同
我想在同一个 pojo 中解组这些文件。
我看到可以在运行时使用
更改编组操作中的元素名称JAXBElement and Qname (like : JAXBElement<Customer> jaxbElement =
new JAXBElement<Customer>(new QName(null, "customer"), Customer.class, customer);)
是否可以在解组时指示运行时根元素的名称?
终极 class :
@XmlRootElement
public class Ulti {
....
}
解组方法:
JAXBContext jaxbContext = JAXBContext.newInstance(Ulti.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
File xmlFile = new File(getFullFileName());
Ulti icc = (Ulti) unmarshaller.unmarshal(xmlFile);
使用 JAXB
class 根元素的名称应该是无关紧要的,您可以更改它并且解组仍然会成功。
示例输入 xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<point>
<x>1</x>
<y>2</y>
</point>
解组代码:
Point p = JAXB.unmarshal(new File("p.xml"), Point.class);
System.out.println(p); // Output: java.awt.Point[x=1,y=2]
现在,如果您再次将根元素更改为 "<p2oint>"
和 运行,您将得到相同的结果,没有任何错误。
您可以在 Unmarshaller
上使用其中一种采用 Class
参数的 unmarshal
方法来获得您正在寻找的行为。通过告诉 JAXB 您要解组的 Class
是什么类型,它不需要通过根元素自己找出一个。
StreamSource xmlSource = new StreamSource(getFullFileName());
JAXBElement<Ulti> jaxbElement = unmarshaller.unmarshal(xmlSource, Ulti.class);
Ulti icc = jaxbElement.getValue();
注:
使用 Unmarshaller.unmarshal(Source, Class)
优于 JAXB.unmarshal(File, Class)
的优势在于通过创建可重复使用的 JAXBContext
仅处理一次元数据的性能优势。