如何使用XStream解析XML中具有相同字段名称但名称空间不同的两个元素?

时间:2019-02-19 06:50:39

标签: xstream

我正在使用XStream对Java类进行序列化和反序列化,以将Java类与XML进行设备接口(NETCONF)的交互。到目前为止,效果很好,但最近我遇到了障碍。

有一个类似XML的XML,它具有两个具有相同名称“ a”但元素名称空间不同的元素。不幸的是,我无法使用设备的XML模式。

MapEntry(Symbol("unaryMinus"): VariableMirror on 'unaryMinus')
MapEntry(Symbol("empty"): VariableMirror on 'empty')
MapEntry(Symbol("hashCode"): MethodMirror on 'hashCode')
MapEntry(Symbol("=="): MethodMirror on '==')
MapEntry(Symbol("unaryMinus"): Instance of '_SyntheticAccessor')
MapEntry(Symbol("empty"): Instance of '_SyntheticAccessor')

我用Google搜索发现StaxDriver是处理名称空间问题所必需的,但是我仍然有DuplicateFieldException。

这些是我的测试代码:

<?xml version="1.0" encoding="utf-8"?>  
<data>  
  <a xmlns="http://site1.net/a">  
    <note>This belongs to namespace 1</note>  
  </a>  
  <a xmlns="http://site2.net/a">  
    <remark>This belongs to namespace 2</remark>  
  </a>  
  <b xmlns="http://site1.net/b">  
    <description>I don't want to create java class for this part</description>  
  </b>  
</data>  

这是异常堆栈跟踪:

public class XStreamTest {
    private static final String FILENAME_DEVICE = "src/test/resources/sample";

    @Test
    public void test() {
        try {
            XStream xstream = new XStream(new StaxDriver());
            xstream.setClassLoader(Thread.currentThread().getContextClassLoader());
            xstream.addPermission(NoTypePermission.NONE);
            xstream.addPermission(NullPermission.NULL);
            xstream.addPermission(PrimitiveTypePermission.PRIMITIVES);
            xstream.allowTypeHierarchy(Collection.class);
            xstream.autodetectAnnotations(true);
            xstream.ignoreUnknownElements();
            xstream.processAnnotations(Data.class);
            xstream.allowTypesByWildcard(new String[] {
                    Data.class.getPackage().getName()+".*"
            });

            String xml = FileUtils.readFileToString(new File(FILENAME_DEVICE), Charset.defaultCharset());
            Data obj = (Data)xstream.fromXML(xml);

            ObjectMapper mapper = new ObjectMapper();
            System.out.print(mapper.writeValueAsString(obj));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

@XStreamAlias("data")
public class Data {
    @XStreamAlias("a")
    public A1 a;

    @XStreamAlias("a")
    public A2 a2;
}

@XStreamAlias("a")
public class A1 {
    @XStreamAsAttribute
    @XStreamAlias("xmlns")
    public final String xmlns = "http://site1.net/a";

    @XStreamAlias("note")
    public String note;
}

@XStreamAlias("a")
public class A2 {
    @XStreamAsAttribute
    @XStreamAlias("xmlns")
    public final String xmlns = "http://site2.net/a";

    @XStreamAlias("remark")
    public String remark;
}

0 个答案:

没有答案