自定义数据的 XML 序列化

发布于 2025-01-04 02:09:11 字数 382 浏览 3 评论 0原文

我有一个 XML 文件:

<Hand cards="C5,SQ,DQ,H8,C9,H7,S9,D5,DA,CJ,S6,HK,D4">
</Hand>

我定义了一个类

[Serializable()]
[XmlRoot("Hand")]
public class Hand
{
    [XmlAttribute("cards")]
    public List<string> Cards{get;set;}
}

在这种情况下如何将 XML 反序列化为对象?手牌对象结果必须有 Cards = {C5,SQ,DQ,H8,C9,H7,S9,D5,DA,CJ,S6,HK,D4}。

I have a XML file:

<Hand cards="C5,SQ,DQ,H8,C9,H7,S9,D5,DA,CJ,S6,HK,D4">
</Hand>

I define a class

[Serializable()]
[XmlRoot("Hand")]
public class Hand
{
    [XmlAttribute("cards")]
    public List<string> Cards{get;set;}
}

How to deserialize a XML to object in this case? Hand object result must have Cards = {C5,SQ,DQ,H8,C9,H7,S9,D5,DA,CJ,S6,HK,D4}.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

尸血腥色 2025-01-11 02:09:11

你不能。

您可以做的是创建一个属性,该属性将在其 getter/setter 中执行此转换

[XmlIgnore]
public List<string> CardList { get; private set; }

[XmlAttribute("cards")]
public string Cards {
   get { return String.Join(",", CardList); }
   set { CardList = value.Split(",").ToList(); }
}

You cannot.

What you can do is to create a property which will do this conversion in its getter/setter

[XmlIgnore]
public List<string> CardList { get; private set; }

[XmlAttribute("cards")]
public string Cards {
   get { return String.Join(",", CardList); }
   set { CardList = value.Split(",").ToList(); }
}
谁许谁一生繁华 2025-01-11 02:09:11

您可以在 IXmlSerialized 的帮助下完成此操作。在 MSDN 上了解更多相关信息。

这样

[Serializable()]
[XmlRoot("Hand")]
public class Hand : IXmlSerializable {
    [XmlAttribute("cards")]
    public List<string> Cards { get; set; }

    public System.Xml.Schema.XmlSchema GetSchema() { return null; }

    public void ReadXml(XmlReader reader) {
        this.Cards = new List<string>(reader.GetAttribute("cards").Split(','));
    }

    public void WriteXml(XmlWriter writer) {
        writer.WriteAttributeString("cards", 
             string.Join(",", 
                this.Cards != null ? this.Cards : new List<string>()));
    }
}

希望对您有帮助。

You can do this with the help of IXmlSerializable. Read more about it on MSDN.

This way

[Serializable()]
[XmlRoot("Hand")]
public class Hand : IXmlSerializable {
    [XmlAttribute("cards")]
    public List<string> Cards { get; set; }

    public System.Xml.Schema.XmlSchema GetSchema() { return null; }

    public void ReadXml(XmlReader reader) {
        this.Cards = new List<string>(reader.GetAttribute("cards").Split(','));
    }

    public void WriteXml(XmlWriter writer) {
        writer.WriteAttributeString("cards", 
             string.Join(",", 
                this.Cards != null ? this.Cards : new List<string>()));
    }
}

Hope this helps you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文