1

I'm trying to parse an xml array, that has an attribute in a weird place.

Here is my(found somewhere on stackowerflow) parser code:

public static string Serialize (object objectToSerialize)
{
    MemoryStream mem = new MemoryStream ();          
    XmlSerializer ser = new XmlSerializer (objectToSerialize.GetType ());         
    ser.Serialize (mem, objectToSerialize);     
    UTF8Encoding utf = new UTF8Encoding ();
    return utf.GetString (mem.ToArray ());
}

public static T Deserialize<T> (string xmlString)
{
    byte[] bytes = Encoding.UTF8.GetBytes (xmlString);
    MemoryStream mem = new MemoryStream (bytes);         
    XmlSerializer ser = new XmlSerializer (typeof(T));
    return (T)ser.Deserialize (mem);
}

This works well in all cases(that I need), except here:

<hr>
    <type n="easy">
        <scores>
            <country name="USA">
                <score nickname="steve" rank="1">1982</score>
                <score nickname="bill" rank="2">1978</score>
...

This is my template class:

public class CountryList
{
    public CountryList ()
    {
    }

    [XmlArray("country")]
    [XmlArrayItem("score")]
    public ScoreAndRank[]
        country;

    [XmlAttribute("name")]
    public string
        name;
    }
}

The score array is parsed correctly, but "name" is always null. I can even get the value of n out, (as [XmlAttribute("n")]). Any tips how to solve this?

edit:solution based on Svein Fidjestøl's link

[XmlType("country")]
public class ScoreContainer
{
    public ScoreContainer ()
    {
    }
    [XmlElement("score")]
    public ScoreAndRank[] country;

    [XmlAttribute("name")]
    public string name;

}

Works like a charm.

Tamas
  • 360
  • 1
  • 4
  • 13

1 Answers1

2

In order to add XML attributes to XML arrays, you need to declare a class for the array element.

A more detailed answer can be found here: How do I add a attribute to a XmlArray element (XML Serialization)?

Community
  • 1
  • 1
Svein Fidjestøl
  • 3,106
  • 2
  • 24
  • 40