如何反序列化的XML文档用prefixed命名空间,但没有NS-prefixed元素呢? [英] How to deserialize an XML doc with a prefixed namespace but no ns-prefixed elements?
问题描述
予有来自外部源的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(命名空间=http://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屋!