我该如何反序列化XML使用默认的命名空间? [英] How can I deserialize xml with a default namespace?

查看:239
本文介绍了我该如何反序列化XML使用默认的命名空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想反序列化由内部系统中的一个产生一个Atom XML。但是,当我尝试:

I am trying to deserialize an Atom xml generated by one of the internal systems. However, when I try:

    public static MyType FromXml(string xml)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(MyType ));
        return (MyType) serializer.Deserialize(new StringReader(xml));
    }

它抛出的命名空间的定义异常:

it throws an exception on the definition of the namespace:

System.InvalidOperationException: <feed xmlns='http://www.w3.org/2005/Atom'> was not expected.

在我的命名空间添加到XmlSerializer的的构造,我的目标完全是空的:

When I add the namespace to the constructor of the XmlSerializer, my object is completely empty:

    public static MyType FromXml(string xml)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(MyType ), "http://www.w3.org/2005/Atom");
        return (MyType) serializer.Deserialize(new StringReader(xml)); //this will return an empty object
    }

我怎样才能得到它的工作任何想法?

Any ideas how can I get it to work?

推荐答案

这是很难不能够看一下如何你的对象模型关系到XML(每个样品即)调查这一点;但是,你应该能够做这样的事情:

It is hard to investigate this without being able to look at how your object model ties to the xml (i.e. samples of each); however, you should be able to do something like:

[XmlRoot("feed", Namespace = "http://www.w3.org/2005/Atom")]
public class MyType {...}

为有限原子的例子(其中正常工作与一些样本原子我有手):

As a limited atom example (which works fine with some sample atom I have "to hand"):

class Program
{
    static void Main()
    {
        string xml = File.ReadAllText("feed.xml");
        XmlSerializer serializer = new XmlSerializer(typeof(MyType));
        var obj = (MyType)serializer.Deserialize(new StringReader(xml));
    }
}
[XmlRoot("feed", Namespace = "http://www.w3.org/2005/Atom")]
public class MyType
{
    [XmlElement("id")]
    public string Id { get; set; }
    [XmlElement("updated")]
    public DateTime Updated { get; set; }
    [XmlElement("title")]
    public string Title { get; set; }
}

这篇关于我该如何反序列化XML使用默认的命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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