如何在 C# 中将 XML 元素反序列化为具有属性和文本的元素数组? [英] How can I deserialise an XML element into an array of elements with both attributes and text in C#?

查看:27
本文介绍了如何在 C# 中将 XML 元素反序列化为具有属性和文本的元素数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试反序列化此 XML 时遇到问题:

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>

使用代码:

[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;
    }
}

基本上,我需要将元素的文本内容放入 Links.Link 但我正在尝试的属性 [XmlText] 不提供我想要的行为期望,我收到错误:

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:

反映字段链接"时出错..

如果有人能指出我方法的错误,我将不胜感激!

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

谢谢.

推荐答案

也许就用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.

(我也切换到一个属性,但这不是问题 - string 是大问题;但是有很多的理由使用属性而不是字段,并且使用自动属性(C# 3.0)几乎没有理由不这样做)

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

另外,尝试查看最内部的异常;在这种情况下,消息是:

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

无法序列化 LinksInterface.LinkElement 类型的成员Link".XmlAttribute/XmlText 不能用于编码复杂类型.

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

这给出了问题所在的合理指示;-p

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

这篇关于如何在 C# 中将 XML 元素反序列化为具有属性和文本的元素数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆