简体   繁体   English

如何使用默认名称空间反序列化xml?

[英]How can I deserialize xml with a default namespace?

I am trying to deserialize an Atom xml generated by one of the internal systems. 我正在尝试反序列化由内部系统之一生成的Atom xml。 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.

When I add the namespace to the constructor of the XmlSerializer, my object is completely empty: 当我将名称空间添加到XmlSerializer的构造函数时,我的对象完全为空:

    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? 有什么想法可以使它正常工作吗?

It is hard to investigate this without being able to look at how your object model ties to the xml (ie samples of each); 如果无法查看您的对象模型如何与xml联系(即每个示例),就很难对此进行调查。 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; }
}

You may debug the XML serialization by adding this to the app.config 您可以通过将XML序列化添加到app.config中来对其进行调试

<system.diagnostics>
  <switches>
    <add name="XmlSerialization.Compilation" value="1" />
  </switches>
</system.diagnostics>

In your temp-folder, C# files for the serializer are generated and you can open up these in VS for debugging. 在临时文件夹中,将生成用于序列化程序的C#文件,您可以在VS中打开这些文件进行调试。

Also have a look at the XmlNamespaceManager (even for default namespaces). 还可以查看XmlNamespaceManager (甚至对于默认名称空间)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM