2013-05-08 74 views
2

我在添加名称空间给属性一段时间后遇到问题。我的要求是创建XML,它将具有子元素而不是根元素的名称空间uri。我用eclipselink moxy,jdk7使用jaxb。jaxb xmlElement命名空间不工作

<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

谢谢

回答

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> 

更多信息

+0

感谢快速回复。我尝试了您在博客上提供的所有示例。不幸的是,我需要将xmlns放在子节点上,而不是根节点上。目前我在包级别上设置xmls,因为我也有自定义名称空间前缀的要求。有没有其他方式/调整将名称空间放在子节点上而不是根节点上? – user2361862 2013-05-08 11:26:51

+0

@ user2361862 - 您的XML文档的哪一部分由该命名空间限定?在你的问题没有。 – 2013-05-08 11:30:31

+0

我同意但客户的文件具有该要求。可能是我应该再次验证xml ..谢谢你的帮助。由于这是我第一次使用jaxb和moxy,因此你的博客帮了我很大的忙。 – user2361862 2013-05-08 11:44:14