反序列化XML,如何访问属性? [英] Deserializing XML, how do I access attributes?

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

问题描述

我有一些正在使用和反序列化的XML.

I have some XML that I am consuming and deserializing.

<Foo>
    <Bars Baz="9">
        <Bar>...</Bar>
        <Bar>...</Bar>
    </Bars>
</Foo>

当前我将其反序列化为此类:

Currently I deserialize it to this class:

[XmlRoot("Foo")]
public class Foo
{
    public Foo() { }

    [XmlArrayItem("Bar")]
    public Bar[] Bars { get; set; }
}

这很好,除了我没有捕获 @Baz 的值.我想将 Baz 添加为 Foo 的属性,但不确定如何.我应该在我的 Baz 属性上设置什么属性以正确地反序列化xml?

This works fine, except that I don't capture the value of @Baz. I want to add Baz as a property of Foo, but I'm not sure how. What attribute would I set on my Baz property to properly deserialize the xml?

[WhatAttributeGoesHere("?")]
public int Baz { get; set; }

推荐答案

通常:

[XmlAttribute]

(带有可选名称,名称空间等)是您想要的.

(with optional name, namespace, etc) is what you are after.

但是,您不能直接在集合上使用它.相反,您需要具有Bars的包装器类,并具有属性和a:

However, you can't use that directly on a collection. You would need instead to have a wrapper class for Bars, with the attribute and a:

public class Foo {
    public BarWrapper Bars {get;set;}
}
public class BarWrapper {
    private readonly List<Bar> bars = new List<Bar>();
    [XmlElement("Bar")]
    public List<Bar> Items {get{return bars;}}

    [XmlAttribute]
    public int Baz {get;set;}
}
public class Bar {...}

这篇关于反序列化XML,如何访问属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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