2016-08-08 55 views
1

我有類文件,說「com.main.module.Test.java」。我需要將此文件轉換爲xml。如果我使用javax.xml.bind.JAXB,返回的XML看起來像:需要jaxb到xml返回xml全包名稱

<Test> 
<sample> 
</sample> 
</Test> 

但我需要的XML將顯示如下:

<com.main.module.Test> 
<com.main.module.sample> 
</com.main.module.sample> 
</com.main.module.Test> 

回答

1

您可以命名你想要的任何元素,只要它是一個valid name

例子:

@XmlRootElement(name = "com.main.module.Test") 
class Foo { 
    @XmlElement(name = "com.main.module.sample") 
    String bar; 

    public static void main(String[] args) throws Exception { 
     Foo foo = new Foo(); 
     foo.bar = "Hello World"; 

     Marshaller marshaller = JAXBContext.newInstance(Foo.class).createMarshaller(); 
     marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
     marshaller.marshal(foo, System.out); 
    } 
} 

輸出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<com.main.module.Test> 
    <com.main.module.sample>Hello World</com.main.module.sample> 
</com.main.module.Test> 

正如你所看到的,根元素名稱無關與類名和子元素的名稱有無關字段名稱。

+0

謝謝。有效。 – Ismail