Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

I have two classes People.java and PeopleMain.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

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);    
    }
}

My output on console on running PeopleMain.java comes as:

<com.test.People>
  <name>Manish Sharma</name>
  <age>21</age>
</com.test.People>

but I want an output as

<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>

What changes should I make in my People.java file to get the desired output?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
142 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;

}

For More Information


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...