2013-05-08 101 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