我想将xml属性转换为tag。例如使用XStream
<root>
<abc attr1="aaa" attr2="bbb"/>
</root>
要
<root>
<abc>
<attr1>aaa</attr1>
<attr2>bbb</attr2>
</abc>
</root>
任何指针都会有所帮助。
答案 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;
}
}