将命名空间添加到 java 类根元素

时间:2021-02-24 21:28:38

标签: java jaxb

我正在使用 jaxb 将 java 对象转换为 xml。但是,我在将命名空间属性添加到根元素 Position 时遇到了问题。

Java 类是:

        @XmlRootElement(name="Position")
        @XmlAccessorType(XmlAccessType.FIELD)
        public class Position{
    
             @XmlElement(name="Info")
             private String info;
    
    }

jaxb 代码是:

            JAXBContext jaxbContext = JAXBContext.newInstance(Position.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            StringWriter wr = new StringWriter();
            jaxbMarshaller.marshal(obj, wr);
            String output = wr.toString();

生成的输出格式为:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Position>
    
    <Info>
    ....

但是我需要输出为

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Position xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://cmds.wlb3.nam.nsroot.net/xmlschema/ArkRioPositionSchema/v1">
  
  <Info>
   ...

如何将这些 xml 命名空间属性添加到根元素。请任何帮助,不胜感激。

1 个答案:

答案 0 :(得分:1)

您通过在注释上实际指定命名空间来添加命名空间:

@XmlRootElement(name = "Position", namespace = "http://cmds.wlb3.nam.nsroot.net/xmlschema/ArkRioPositionSchema/v1")
@XmlAccessorType(XmlAccessType.FIELD)
class Position{

    @XmlElement(name = "Info", namespace = "http://cmds.wlb3.nam.nsroot.net/xmlschema/ArkRioPositionSchema/v1")
    private String info;

}

输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Position xmlns="http://cmds.wlb3.nam.nsroot.net/xmlschema/ArkRioPositionSchema/v1">
    <Info>Testing...</Info>
</Position>

如果需要,将添加 xsixsd 命名空间,而本示例不需要它们。

请注意,不必在所有注释上指定命名空间,您还可以通过在 package-info.java 文件中添加注释来为整个 java 包指定命名空间。一些研究将很快教你如何。