0

这是我从第三方 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
}

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

/马丁

4

3 回答 3

2

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

REM Infer XSD from XML
xsd.exe myfile.xml

REM Create classes from XSD
xsd.exe myfile.xsd /classes
于 2012-09-07T09:30:16.957 回答
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>.

于 2012-09-07T10:13:03.030 回答
-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);
于 2012-09-07T09:43:57.503 回答