Java 使用简单xml时不需要的类属性
我目前使用的是简单的XML库,本教程没有一个可运行的ElementList示例 我有一个例子:Java 使用简单xml时不需要的类属性,java,xml,Java,Xml,我目前使用的是简单的XML库,本教程没有一个可运行的ElementList示例 我有一个例子: @Root public class Example { @ElementList private List<String> text; @Attribute private int index; public Example() { super(); } public Example(List<String> text, int index) { th
@Root
public class Example {
@ElementList
private List<String> text;
@Attribute
private int index;
public Example() {
super();
}
public Example(List<String> text, int index) {
this.text = text;
this.index = index;
}
public List<String> getMessage() {
return text;
}
public int getId() {
return index;
}
}
@Root
公开课范例{
@元素列表
私有列表文本;
@属性
私有整数索引;
公共示例(){
超级();
}
公共示例(列表文本、整数索引){
this.text=文本;
这个指数=指数;
}
公共列表getMessage(){
返回文本;
}
公共int getId(){
收益指数;
}
}
和一个简单的运行类:
public class M {
public static void main(String[] args) throws Exception {
Serializer serializer = new Persister();
List<String> l = new LinkedList<String>();
l.add("f");
l.add("f");
Example example = new Example(l, 123);
File result = new File("example.xml");
serializer.write(example, result);
}
}
公共类M{
公共静态void main(字符串[]args)引发异常{
Serializer Serializer=new Persister();
列表l=新的LinkedList();
l、 添加(“f”);
l、 添加(“f”);
示例示例=新示例(l,123);
文件结果=新文件(“example.xml”);
serializer.write(示例,结果);
}
}
我生成的XML是:
<example index="123">
<text class="java.util.LinkedList">
<string>f</string>
<string>f</string>
</text>
</example>
F
F
为什么我会得到class=“java.util.LinkedList”?我对如何删除此属性感到困惑。您可以使用VisitorStrategy拦截对象的序列化
Strategy strategy = new VisitorStrategy(new Visitor() {
@Override
public void write(Type type, NodeMap<OutputNode> node) throws Exception {
if ("text".equals(node.getName())){
node.remove("class");
}
}
...
});
Strategy Strategy=新访问者策略(新访问者(){
@凌驾
公共void write(类型,节点映射节点)引发异常{
if(“text”.equals(node.getName())){
节点。移除(“类”);
}
}
...
});
我正在处理同一个问题,我找到了一种避免“class”属性的方法
而不是像这样使用@ElementList:
@ElementList(name="Files", entry="File")
您可以将@Path注释与@ElementList一起使用,如下所示:
@Path(value="Files")
@ElementList(inline=true, entry="File")
尝试使用
@ElementList(name=“list”)
注释或使用任何名称。尝试使用@ElementArray private String[]text
看看这个。我通过private String[]text尝试了您的建议。我用字符串[]stockArr={“fd”,“fd”}编辑了我的M.java;示例=新示例(stockArr,123);然后我得到了一个java.lang.ClassCastException:[Ljava.lang.String;无法转换为java.util.Collection]。但是,是的,我做了教程,但没有给出如何在使用listelement时在主文件中生成XML的示例。