嵌套List C#的XML反序列化

时间:2017-03-13 08:57:49

标签: c# xml deserialization xml-deserialization

我正在尝试使用XmlSerializer反序列化Xml文件。 我文件的一部分如下所示:

package Exceptie;
import java.util.Scanner;

public class Program {   

    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        int n=0;

        while(n==0){
            try {
                n=Integer.parseInt(input.nextLine());
                if (n==0) break;
            }catch(Exception e){
                System.out.println("not int, read again");
            }
        }
    }
}

我尝试了不同的方法,但它不起作用。

我的第一次尝试看起来像:

<bla>
    <ListOfListOfTest>
         <ListOfTest> 
               <Test>       
               </Test>        
        </ListOfTest>        
    </ListOfListOfTest>
</bla>

- &GT;不起作用。

第二次尝试:

public class bla
    {
        public bla()
        {
            ListOfListOfTest = new List<List<Test>>();
        }
        [...]
        public List<List<Test>> ListOfListOfTest{ get; set; }            
    }

- &GT;也失败了

第三次尝试:

public class bla
    {
        public bla()
        {
            ListOfListOfTest = new List<List<Test>>();
        }
        [..]
        public List<List<Test>> ListOfListOfTest { get; set; }

        [XmlArrayItemAttribute]
        public List<List<Test>> listOfListOfTest { get { return ListOfListOfTest ; } }
    }

- &GT;失败...

失败表示public class bla { public bla() { ListOfListOfTest = new List<Foo>(); } [...] public List<Foo> ListOfListOfTest { get; set; } } public class Foo { public Foo() { ListOfTest = new List<Test>(); } public List<Test> ListOfTest { get; set; } } 期间XmlSerializer未填充List。 我总是得到serializer.Deserialize(),其中包含零元素。

我做错了什么?

感谢您的努力

3 个答案:

答案 0 :(得分:1)

这样的东西?

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;

class Program {
    static void Main() {
        var xml = @"<bla>
    <ListOfListOfTest>
         <ListOfTest> 
               <Test>       
               </Test>        
        </ListOfTest>        
    </ListOfListOfTest>
</bla>";
        var bar = (Bar)new XmlSerializer(typeof(Bar)).Deserialize(new StringReader(xml));
        Console.WriteLine(bar.Lists.Sum(_ => _.Items.Count)); // 1
    }
}
[XmlRoot("bla")]
public class Bar {
    [XmlArray("ListOfListOfTest")]
    [XmlArrayItem("ListOfTest")]
    public List<Foo> Lists { get; } = new List<Foo>();
}
public class Foo {
    [XmlElement("Test")]
    public List<Test> Items { get; } = new List<Test>();
}
public class Test { }

实际布局取决于可能重复的元素,以及是否需要能够重现确切的组织(而不仅仅是想要所有Test项)。在上面的代码中,预计ListOfListOfTest不会重复,但可以有任意数量的ListOfTestTest元素。

答案 1 :(得分:1)

要了解正确反序列化后XML的外观,请复制XML:

In [9]: #just a test signal
   ...: signal = np.random.random(size=251)
   ...: y = np.arange(0.0108, 0.0135, 0.001)
   ...: x = np.arange(0, (len(signal)))
   ...: 

# Original approach
In [10]: %%timeit I_avg = np.zeros(len(y))
    ...: Q_avg = np.zeros_like(I_avg)
    ...: for i in range(0, len(y)):
    ...:     I_avg[i] = np.array(signal * (np.cos(2 * np.pi * y[i] * x))).sum()
    ...:     Q_avg[i] = np.array(signal * (np.sin(2 * np.pi * y[i] * x))).sum()
    ...: 
10000 loops, best of 3: 68 µs per loop

# Proposed approach
In [11]: %%timeit mult = 2*np.pi*y[:,None]*x
    ...: I_avg, Q_avg = np.cos(mult).dot(signal), np.sin(mult).dot(signal)
    ...: 
10000 loops, best of 3: 34.8 µs per loop

在C#中创建一个类。单击顶部的“编辑”,然后在光标位于类中时“粘贴特殊”,然后“将XML粘贴为类”。 Visual Studio将为您正确地反序列化XML并创建必要的类。使用它来比较您认为需要的内容以及实际需要的内容,以便自己澄清反序列化应该如何工作。

答案 2 :(得分:1)

Visual Studio有一个方便的选项 - 您只需复制粘贴xml并转到菜单编辑&gt;选择性粘贴&gt;将XML粘贴为类。 Visual Studio将生成可用于序列化/反序列化xml的类。在这种特殊情况下,它将生成:

[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class bla
{
    private blaListOfListOfTest listOfListOfTestField;

    public blaListOfListOfTest ListOfListOfTest
    {
        get { return this.listOfListOfTestField; }
        set { this.listOfListOfTestField = value; }
    }
}

[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class blaListOfListOfTest
{
    private blaListOfListOfTestListOfTest listOfTestField;

    public blaListOfListOfTestListOfTest ListOfTest
    {
        get { return this.listOfTestField; }
        set { this.listOfTestField = value; }
    }
}

[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class blaListOfListOfTestListOfTest
{
    private object testField;

    public object Test
    {
        get { return this.testField; }
        set { this.testField = value; }
    }
}

之后你可以做一些调整 - 例如删除类型限定符或用自动属性替换属性(可以使用visual studio扩展)。几次击键后:

[Serializable]
[DesignerCategory("code")]
[XmlType(AnonymousType = true)]
[XmlRoot(Namespace = "", IsNullable = false)]
public partial class bla
{
    public blaListOfListOfTest ListOfListOfTest { get; set; }
}

[Serializable]
[DesignerCategory("code")]
[XmlType(AnonymousType = true)]
public partial class blaListOfListOfTest
{
    public blaListOfListOfTestListOfTest ListOfTest { get; set; }
}

[Serializable]
[DesignerCategory("code")]
[XmlType(AnonymousType = true)]
public partial class blaListOfListOfTestListOfTest
{
    public object Test { get; set; }
}

反序列化将如下所示:

var serializer = new XmlSerializer(typeof(bla));
var blaObj = serializer.Deserialize(new StringReader(xmlString));