简体   繁体   English

在C#中解析xml

[英]Parsing xml in C#

I have the following xml doc that I am trying to parse: 我有以下要解析的xml文档:

<report>
    <fruit name="Apple" count="5"/>
    <vegetable name="Potato" count="2"/>
    <vegetable name="Tomato" count="3"/>
    <fruit name="Orange" count="0"/>
</report>

I have the following class to deserialize: 我有以下课程要反序列化:

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class report
{

private object[] itemsField;

/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("fruit", typeof(reportFruit))]
[System.Xml.Serialization.XmlElementAttribute("vegetable", typeof(reportVegetable))]
    public object[] Items
    {
        get
        {
            return this.itemsField;
        }
        set
        {
            this.itemsField = value;
        }
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class reportFruit
{

    private string nameField;

    private byte countField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string name
    {
        get
        {
            return this.nameField;
        }
        set
        {
            this.nameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public byte count
    {
        get
        {
            return this.countField;
        }
        set
        {
            this.countField = value;
        }
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class reportVegetable
{

    private string nameField;

    private byte countField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string name
    {
        get
        {
            return this.nameField;
        }
        set
        {
            this.nameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public byte count
    {
        get
        {
            return this.countField;
        }
        set
        {
            this.countField = value;
        }
    }
}

How can I iterate through the fruits and vegetables after it has been deserialized? 水果和蔬菜反序列化后如何遍历水果和蔬菜?

foreach (string name in instance.Items) // doesnt work    

You can do this: 你可以这样做:

for(int i = 0; i < instance.Items.Length; i++)
{
    object item = instance.Items[i];
    if(item is reportFruit) {
       // it is a fruit!!!
       reportFruit fruit = (reportFruit)item;
    }
    if(item is reportVegetable) {
       // it is not a fruit :'(
       reportVegetable vegetable = (reportVegetable)item;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM