【问题标题】:jaxb xmlElement namespace not workingjaxb xmlElement 命名空间不起作用
【发布时间】:2013-05-08 10:47:17
【问题描述】:

一段时间以来,我一直无法将命名空间添加到属性。我的要求是创建 xml,它将在子元素而不是根元素上具有命名空间 uri。我正在使用 jaxb 和 eclipselink moxy,jdk7。

<document>
<Date> date </Date>
</Type>type </Type>
<customFields xmlns:pns="http://abc.com/test.xsd">
  <id>..</id>
  <contact>..</contact>
</customFields>
</document>

Classes are:

@XmlRootElement(name = "document")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder = {"type","date", "customFields"})
public class AssetBean {

@XmlElement(name="Type")
private String type;
@XmlElement(name="Date")


@XmlElement(name = "CustomFields",namespace = "http://api.source.com/xsds/path/to/partner.xsd")    
private CustomBean customFields = new CustomBean();

//getters/setters here

}

public class CustomBean {

 private String id;
 private String contact;
 //getter/setter
}
package-info.java
@javax.xml.bind.annotation.XmlSchema (        
 xmlns = { 
 @javax.xml.bind.annotation.XmlNs(prefix="pns",
           namespaceURI="http://api.source.com/xsds/path/to/partner.xsd")
 },
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.UNQUALIFIED
)
package com.abc.xyz

我按照这篇文章寻求帮助,但无法得到我正在尝试的内容 http://blog.bdoughan.com/2010/08/jaxb-namespaces.html

谢谢

【问题讨论】:

    标签: namespaces jaxb


    【解决方案1】:

    域模型(根)

    在下面的域对象中,我将使用 @XmlElement 注释将命名空间分配给其中一个元素。

    import javax.xml.bind.annotation.*;
    
    @XmlRootElement
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Root {
    
        String foo;
    
        @XmlElement(namespace="http://www.example.com")
        String bar;
    
    }
    

    演示代码

    在下面的演示代码中,我们将创建域对象的实例并将其编组为 XML。

    import javax.xml.bind.*;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            JAXBContext jc = JAXBContext.newInstance(Root.class);
    
            Root root = new Root();
            root.foo = "FOO";
            root.bar = "BAR";
    
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(root, System.out);
        }
    
    }
    

    输出

    下面是运行演示代码的输出。我们使用 @XmlElement 注释分配命名空间的元素是适当的命名空间限定的,但命名空间声明出现在根元素上。

    <?xml version="1.0" encoding="UTF-8"?>
    <root xmlns:ns0="http://www.example.com">
       <foo>FOO</foo>
       <ns0:bar>BAR</ns0:bar>
    </root>
    

    更多信息

    【讨论】:

    • 感谢您的快速回复。我尝试了您在博客上提供的所有示例。不幸的是,我需要 xmlns 位于子节点而不是根节点上。目前我在包级别设置 xmls,因为我还需要自定义命名空间前缀。有没有其他方法/调整将命名空间放在子节点而不是根节点上?
    • @user2361862 - 您的 XML 文档的哪一部分由该命名空间限定?在你的问题中什么都不是。
    • 我同意,但客户的文件有这个要求。也许我应该再次验证那个 xml.. 谢谢你的帮助。您的博客极大地帮助了我,因为这是我第一次使用 jaxb 和 moxy。
    猜你喜欢
    • 2018-03-06
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 2013-07-21
    • 2014-06-07
    • 2010-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多