如何反序列化的XML文档用prefixed命名空间,但没有NS-prefixed元素呢? [英] How to deserialize an XML doc with a prefixed namespace but no ns-prefixed elements?

查看:305
本文介绍了如何反序列化的XML文档用prefixed命名空间,但没有NS-prefixed元素呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

予有来自外部源的XML文档。

I have an XML document from an external source.

<?xml version="1.0" encoding="utf-8"?>
<ns0:Info xmlns:ns0="http://www.ZomboCorp.com/">
  <Name>Anthony</Name>
  <Job>Developer</Job>
</ns0:Info>

我要反序列化到这样一个对象。

I need to deserialize it into an object like this.

public class Info
{
    public String Name { get; set; }
    public String Job { get; set; }
}

用于为是,则串行抛出 InvalidOperationException异常

&LT;信息的xmlns =' http://www.ZomboCorp.com/&GT; 是没有预料到

<Info xmlns='http://www.ZomboCorp.com/'> was not expected.

如果我加入 [的XmlElement(命名空间=htt​​p://www.ZomboCorp.com/)] 类定义的串行返回带有空的属性,一个新的信息对象。

If I add [XmlElement(Namespace = "http://www.ZomboCorp.com/")] to the class definition, the Serializer returns a new Info object with null properties.

推荐答案

我用的 XSD.EXE 的(一个VS工具)和生成从XML文件的模式,然后从架构的类文件。它建议

I used xsd.exe (a VS tool) and generated a schema from the XML file and then a class file from the schema. It suggested

[XmlType(AnonymousType = true, Namespace = "http://www.ZomboCorp.com/")]
[XmlRoot(Namespace = "http://www.ZomboCorp.com/", IsNullable = false)]
public class Info
{
    [XmlElement(Form = XmlSchemaForm.Unqualified)]
    public String Name { get; set; }
    [XmlElement(Form = XmlSchemaForm.Unqualified)]
    public String Job { get; set; }
}

不过,我能逃脱

But, I was able to get away with

[XmlType(AnonymousType = true)]
[XmlRoot(Namespace = "http://www.ZomboCorp.com/")]
public class Info
{
    [XmlElement(Form = XmlSchemaForm.Unqualified)]
    public String Name { get; set; }
    [XmlElement(Form = XmlSchemaForm.Unqualified)]
    public String Job { get; set; }
}

这篇关于如何反序列化的XML文档用prefixed命名空间,但没有NS-prefixed元素呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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