Define namespaces tags so that generated XML have those tags?

假装没事ソ 提交于 2019-12-11 07:00:02

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/20250036/define-namespaces-tags-so-that-generated-xml-have-those-tags

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!