我的类应该如何使用xmlserializer从这个xml看起来?

时间:2012-09-07 09:27:06

标签: c# xml xml-serialization

这是我从第三部分api回来的xml:

<data>
    <installations>
        <installation>
            <reader>1</reader>
            <reader>2</reader>
            <reader>3</reader>
            <reader>4</reader>
        </installation>
    </installations
</data>

这些是我现在的课程

public class data
{
    public List<installation> installations
}

public class installation
{
    // HERE I DON'T KNOW HOW TO DO THE <reader> STUFF
}

我希望有人知道应该怎么做

/马丁

3 个答案:

答案 0 :(得分:2)

您可以使用XSD.exe自动为您创建课程:

REM Infer XSD from XML
xsd.exe myfile.xml

REM Create classes from XSD
xsd.exe myfile.xsd /classes

答案 1 :(得分:1)

您的课程可能如下所示:

public class data
{
    public List<installation> installations { get; set; }
    public data() { installations = new List<installation>(); }
}

public class installation
{
    [XmlElement("reader")]
    public List<reader> reader { get; set; }
    public installation() { reader = new List<reader>(); }
}

public class reader
{
    [XmlTextAttribute]
    public Int32 value {get;set;}
}

这里有两件事很重要:

  1. 使用XmlElement("reader")隐藏因<reader></ reader>属性而原本会创建的List<reader> reader个节点。

  2. 使用XmlTextAttribute<reader><value>1</value></reader>创建为<reader>1</reader>

答案 2 :(得分:-1)

public class data 
{
List<List<reader>> installations = new List<List<reader>>();
List<reader> installation = new List<reader>();
installation.Add(new reader());
installation.Add(new reader());
installation.Add(new reader());
installation.Add(new reader());
installations.Add(installation);
}

public class data
{
    public List<installation> installations
}

public class installation : List<reader>
{
    public void AddReader(reader obj)
    {
        this.Add(obj);
    }
}

等方式,不使用XmlSerializer(typeof(UnknownClass))自定义解析xml:

使用LINQ to Xml;

XDocument doc = XDocument.Parse(xmlTextFromThirdParty);