简体   繁体   中英

Parsing xml in C#

I have the following xml doc that I am trying to parse:

<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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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