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 Si开发者_运维技巧te 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.
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
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.
精彩评论