【发布时间】:2016-05-02 06:54:59
【问题描述】:
考虑以下代码:
Main.java
====
package com.sample;
import com.sample.entity.Customer;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class Main {
public static void main(String[] args) throws JAXBException {
JAXBContext jc = JAXBContext.newInstance(Customer.class);
Customer customer = new Customer();
customer.setId(123);
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(customer, System.out);
}
}
Customer.java
====
package com.sample.entity;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Customer {
private long id;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
package-info.java
====
@XmlSchema(namespace = "http://www.example.org/package", elementFormDefault = XmlNsForm.QUALIFIED)
package com.sample.entity;
import javax.xml.bind.annotation.XmlSchema;
import javax.xml.bind.annotation.XmlNsForm;
我希望重用 Customer POJO 并创建两个不同的命名空间值。所以首先我想打印输出
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer xmlns="http://www.example.org/package">
<id>123</id>
</customer>
像当前代码一样,然后使用来自同一个 pojo 的不同主命名空间创建第二个 xml,如下所示
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer xmlns="http://www.another.org/package">
<id>123</id>
</customer>
或一起删除命名空间
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer>
<id>123</id>
</customer>
【问题讨论】:
-
您应该为 @XmlSchema 部分添加一个额外的代码 sn-p,因为它非常相关,但很容易被忽略。
标签: java xml xsd jaxb marshalling