Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I deserialise an XML element into an array of elements with both attributes and text in C#?

Tags:

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</link>
    <link title="eBay">http://ebay.co.uk</link>
    <link title="Best Damn Site on the Web">http://stackoverflow.com</link>
</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.

like image 493
Ryall Avatar asked Nov 18 '09 10:11

Ryall


1 Answers

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

like image 168
Marc Gravell Avatar answered Oct 14 '22 22:10

Marc Gravell