如何配置 XML 反序列化器来获取属性?

发布于 2024-12-17 17:38:39 字数 1106 浏览 3 评论 0原文

可能的重复:
反序列化 XML,如何访问属性?

我正在反序列化以下内容XML:

<root>
  <foo> some content </foo>
  <bar id="someId">someContent</bar>
</root>

使用 XMLSerializer 转换为下面的 Class 对象。

[XmlRootAttribute("foobar")]
public class foobar
{

    [XmlElementAttribute("foo")]
    public string foo { get; set; }

    [XmlElementAttribute("bar")]
    public string bar { get; set; }        

}

但是,这不会拾取 bar 标记内的 someId。我还需要做出什么改变才能接受它?

我尝试了这个:

在上面的类中,我将第二个属性更改为:

[XmlElementAttribute("bar")]
public Bar bar { get; set; } 

然后定义了一个新类:

[XmlTypeAttribute]
    public class Bar
    {
        [XmlAttribute("id")]
        public string id { get; set; }

        [XmlText]
        public string Value { get; set; }
    }

这仍然会获取该值,但不会获取Id

Possible Duplicate:
Deserializing XML, how do I access attributes?

I am deserializing the following XML:

<root>
  <foo> some content </foo>
  <bar id="someId">someContent</bar>
</root>

Into a Class object below using XMLSerializer.

[XmlRootAttribute("foobar")]
public class foobar
{

    [XmlElementAttribute("foo")]
    public string foo { get; set; }

    [XmlElementAttribute("bar")]
    public string bar { get; set; }        

}

However, this does not pick up someId within the bar tag. What change do I need to make to pick it up as well?

I tried this:

In the class above, I changed the second property to:

[XmlElementAttribute("bar")]
public Bar bar { get; set; } 

And then defined a new class:

[XmlTypeAttribute]
    public class Bar
    {
        [XmlAttribute("id")]
        public string id { get; set; }

        [XmlText]
        public string Value { get; set; }
    }

This still picks up the value but not the Id.

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

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

发布评论

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

评论(1

梦途 2024-12-24 17:38:39

尝试使用不带(“id”)的 XmlAttribute 应该修复它。

try to use XmlAttribute without ("id") that should fix it.

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