在java中将属性转换为Tag

时间:2010-12-15 19:25:43

标签: java xml xstream

  

可能重复:
  Convert all node's attributes into child nodes

我想将xml属性转换为tag。例如使用XStream

    <root>
       <abc attr1="aaa" attr2="bbb"/>
    </root>

    <root>
       <abc>
         <attr1>aaa</attr1>
         <attr2>bbb</attr2>
       </abc>
    </root>

任何指针都会有所帮助。

1 个答案:

答案 0 :(得分:0)

只要使用XStream,就无法直接转换它。如果要使用XStream,则必须创建与XML元素对应的类。

[阅读]

XStream xs = new XStream(new DomDriver());
xs.alias("root", ParentElement.class);
xs.useAttributeFor(ChildElement.class, "aaa"); // read as attribute
xs.useAttributeFor(ChildElement.class, "bbb");

ParentElement parent = new ParentElement();
try {
    FileInputStream fis = new FileInputStream("readfile");
    xs.fromXML(fis, parent);
} catch (FileNotFoundException ex) {
    ex.printStackTrace();
}

[写]

ChildElement element = new ChildElement();
element.setAttr1("aaa");
element.setAttr2("bbb");

ParentElement parent = new ParentElement();
parent.setChildElement(element);

XStream xs = new XStream();
xs.alias("root", ParentElement.class);

try {
    FileOutputStream fs = new FileOutputStream("writefile");
    xs.toXML(parent, fs);
} catch (FileNotFoundException e1) {
    e1.printStackTrace();
}

[ParentElement]

public class ParentElement {
    private ChildElement abc;
    public void setChildElement(ChildElement child) {
        this.abc = child;
    }
}

[是childElement]

public class ChildElement {
    private String attr1;
    private String attr2;

    public String getAttr1() {
        return attr1;
    }
    public void setAttr1(String attr1) {
        this.attr1 = attr1;
    }

    public String getAttr2() {
        return attr2;
    }
    public void setAttr2(String attr2) {
        this.attr2 = attr2;
    }
}