如何使用JAXB输出带命名空间的xml? [英] How to use JAXB to output an xml with Namespaces?
问题描述
与前一个问题相比,我可能会重复这个问题(定义名称空间标签,以便生成的XML具有这些标签?),但由于在我之前的问题中,此范围仅限于XStream,这就是我需要提出这个新问题的原因。
May be I am repeating this question as compared to previous question(Define namespaces tags so that generated XML have those tags?), but since in my previous question this scope gets limited to XStream that is why I need to ask this new question.
我有两个类People.java和PeopleMain.java
I have two classes People.java and PeopleMain.java
People.java
People.java
package com.test;
public class People {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
PeopleMain.java
PeopleMain.java
package com.test;
import com.thoughtworks.xstream.XStream;
public class PeopleMain {
public static void main(String args[]){
People p= new People();
p.setAge("21");
p.setName("Manish Sharma");
String xml = //JAXB code to get xml from Person p object
System.out.println(xml);
}
}
运行PeopleMain.java时我在控制台上的输出是:
My output on console on running PeopleMain.java comes as:
<com.test.People>
<name>Manish Sharma</name>
<age>21</age>
</com.test.People>
但我希望输出为
<People xmlns:ns2="http://example.com/foo" xmlns:ns3="http://example.com/bar">
<ns2:name>Manish Sharma</ns2:name>
<ns3:age>21</ns3:age>
</People>
我应该在People.java文件中进行哪些更改才能获得所需的输出?
What changes should I make in my People.java file to get the desired output?
推荐答案
您可以执行以下操作并在 @XmlElement
注释中指定命名空间:
You can do the following and specify the namespace on the @XmlElement
annotation:
import javax.xml.bind.annotation.*;
@XmlRootElement(name="People")
@XmlAccessorType(XmlAccessType.FIELD)
public class People {
@XmlElement(namespace="http://example.com/foo")
private String name;
@XmlElement(namespace="http://example.com/bar")
private int age;
}
更多信息
- http://blog.bdoughan.com/2010/08/jaxb-namespaces.html
- http://blog.bdoughan.com/2011/11/jaxb-and-namespace-prefixes.html
- http:/ /blog.bdoughan.com/2010/10/how-does-jaxb-compare-to-xstream.html
- http://blog.bdoughan.com/2010/08/jaxb-namespaces.html
- http://blog.bdoughan.com/2011/11/jaxb-and-namespace-prefixes.html
- http://blog.bdoughan.com/2010/10/how-does-jaxb-compare-to-xstream.html
这篇关于如何使用JAXB输出带命名空间的xml?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!