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.

1 Answer 1

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)?

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it works now. I've added the solution to the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.