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

        XStream xs =new XStream();

        String xml = xs.toXML(p);

        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?

Was it helpful?

Solution

Unfortunately, per the XSTream FAQ, XStream does not support XML namespaces unless using a StAX parser.

Not every XML parser supports namespaces and not every XML parser that supports namespaces can be configured within XStream to use those. Basically namespaces must be supported individually for the different XML parsers and the only support for namespaces that has currently been implemented in XStream is for the StAX paser. Therefore use and configure the StaxDriver of XStream to use namespaces.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top