views:

259

answers:

2

I am having a problem trying to deserialise this XML:

<?xml version="1.0" encoding="UTF-8"?>
<links>
    <link title="ABC">http://abc.co.uk&lt;/link&gt;
    <link title="eBay">http://ebay.co.uk&lt;/link&gt;
    <link title="Best Damn Site on the Web">http://stackoverflow.com&lt;/link&gt;
</links>

Using the code:

[XmlRoot("links")]
public class LinksInterface
{
    [XmlElement("link")]
    public List<LinkElement> Links;

    public class LinkElement
    {
        [XmlAttribute("title")]
        public string Title;
        [XmlText] // This bit is the troublesome bit!
        public LinkElement Link;
    }
}

Basically, I need to put the text contents of the element into Links.Link but the attribute I am trying [XmlText] does not provide the behaviour I'd expect and I get the error:

There was an error reflecting field 'Links'..

If anyone could point out the error of my ways, I would be most grateful!

Thanks.

+4  A: 

Perhaps just use string:

[XmlText]
public string Link {get;set;}

At the moment the class is recursive (a tree) - I don't think that is what you intended.

(I also switched to a property, but that isn't the problem - string is the biggie; but there are lots of reasons to use properties instead of fields, and with auto-properties (C# 3.0) there are few excuses not to)


Edit: also, try looking at the inner-most exception; in this case, the message is:

Cannot serialize member 'Link' of type LinksInterface.LinkElement. XmlAttribute/XmlText cannot be used to encode complex types.

That gives a reasonable indication of where the problem is ;-p

Marc Gravell
Doh! Nicely spotted Marc :)
Nat Ryall
Also changed to properties instead of fields. Thanks for the advice.
Nat Ryall
Ignore the -1... clicked the down arrow by mistake, won't let me re-up it... Sorry :S
Nat Ryall
A: 

Check out this article XML Serialization in C#. The author uses a getter/setter to add items to the collection (array in the article) and apply the attribute [XmlElement("link")] to the getter/setter.

Cheers.

mqbt