我看到这个问题已经被问过了,我已经审查了答案,但我应该承认我仍然无法得到想要的输出:(现在我想要的是:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<tokenregistrationrequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="TOKEN">
<purchase>true</purchase>
</tokenregistrationrequest>
我的类定义如下:
@XmlRootElement() //THIS HAS BEEN ADDED MANUALLY
public class Tokenregistrationrequest {
protected boolean purchase;
}
和我已经修改了package-info如下所示:
@javax.xml.bind.annotation.XmlSchema(xmlns = {
@javax.xml.bind.annotation.XmlNs(prefix = "xsi", namespaceURI = "http://www.w3.org/2001/XMLSchema-instance"),
@javax.xml.bind.annotation.XmlNs(prefix = "xs", namespaceURI = "http://www.w3.org/2001/XMLSchema"),
@javax.xml.bind.annotation.XmlNs(prefix = "", namespaceURI = "TOKEN")
})
当我运行代码时,我得到的只是…
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<tokenregistrationrequest>
<purchase>true</purchase>
</tokenregistrationrequest>
我很确定我在这里错过了一些基本的东西…如有任何帮助,不胜感激
编辑:在做更多的测试时,我看到在编译我的测试类JAXB工件时被编译,而不是package-info.java。这是因为this的用法是可选的吗?
欢呼
这个问题已经问了一段时间了,但我刚刚发现自己处于类似的情况。这有点令人不安,但如果你坚持的话,用这种方法是可能的。
你可以手动添加这些属性作为属性到你的实体类。
@XmlAttribute(name = "xmlns")
private String token = "TOKEN";
@XmlAttribute(name = "xmlns:xsd")
private String schema = "http://www.w3.org/2001/XMLSchema";
@XmlAttribute(name = "xmlns:xsi")
private String schemaInstance = "http://www.w3.org/2001/XMLSchema-instance";
那么你应该得到这样的输出:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<tokenregistrationrequest xmlns="TOKEN"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<purchase>true</purchase>
</tokenregistrationrequest>
package Level上的Annotation XmlNs将前缀绑定到命名空间。但是,如果不使用命名空间,就像您的情况一样,命名空间节点将不会被添加到根元素中。
您可能应该将Tokenregistrationrequest放在TOKEN命名空间中:
@XmlRootElement(namespace = "TOKEN") //THIS HAS BEEN ADDED MANUALLY
public class Tokenregistrationrequest {
protected boolean purchase;
这将导致
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<tokenregistrationrequest xmlns="TOKEN">
<purchase>true</purchase>
</tokenregistrationrequest>
其余的前缀声明将不会出现,因为在结果文档中没有来自这些名称空间的节点。如果有,前缀声明也应该序列化。