在vb.net中反序列化XML数组

时间:2016-10-19 13:52:23

标签: xml vb.net xml-deserialization

我需要在VB.NET中反序列化XML文件。

我正在使用标准XML库。 我无法记下vb代码来定义以下结构:

<myvar>
    <var>...</var>
    <troublecodes>
        <troublecode>
        ...
        </troublecode>
        <troublecode>
        ....
        </troublecode>
        <statusbyte>
        ....
        </statusbyte>
        <statusbyte>
        ....
        </statusbyte>
        <statusbyte>
        ....
        </statusbyte>
    </troublecodes>
</myvar>

我的定义是:

Public Class MyVar
  <XmlElement("var")> Public name As String
  <XmlElement("troublecodes")> Public troubleCodes As TroubleCodes
End Class

Public Class TroubleCodes
<XmlArrayItem("troublecode")> Public troubleCode() As TroubleCode
<XmlArrayItem("statusbyte")> Public statusByte() As StatusByte
End Class

Public Class TroubleCode
  <XmlElement("one")> Public one As String
  <XmlElement("two")> Public two As String
End Class

Public Class StatusByte
  <XmlElement("three")> Public threeAs String
  <XmlElement("four")> Public four As String
End Class

但反序列化不会填充对象 我该如何定义它们?

2 个答案:

答案 0 :(得分:1)

反序列化中的问题通常可以通过序列化根类型的示例并将生成的XML与所需的XML进行比较来诊断。如果我使用您的CFHTTPMessageRef类型(演示fiddle),我会得到以下结果:

MyVar

这有以下问题:

  • 根节点大写不正确。

    可以通过向您的根类型添加<XmlRoot("myvar")>来解决此问题。

  • <MyVar> <var>my name</var> <troublecodes> <troubleCode> <troublecode> <one>one</one> <two>two</two> </troublecode> </troubleCode> <statusByte> <statusbyte> <three>three</three> <four>four</four> </statusbyte> </statusByte> </troublecodes> </MyVar> 有一个额外的嵌套级别。

    默认情况下,<troubleCode>序列化所有集合,包括具有外部容器元素的数组。要禁止外部容器元素并将集合序列化为平面元素序列,请将XmlSerializer属性替换为<XmlElement("troublecode")>

  • XmlArrayItem还有一层额外的嵌套。

因此您的类型应如下:

<statusByte>

修正了fiddle

答案 1 :(得分:1)

我的解决方案是:

public void addAssociation(final Association association) {
    final CountDownLatch latch = new CountDownLatch(1);
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (!associationList.contains(association)) {
                associationArrayAdapter.add(association);
            }
            latch.countDown();
        }
    });
    try {
        latch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    if (!associationList.contains(association)) {
        associationList.add(association);
    }
}

序列化变量我获得了相同的XML代码。