【发布时间】:2016-06-24 16:47:25
【问题描述】:
我正在尝试在 C# 中使用 XmlSerializer 反序列化 XML 文件。
随后的目标类是使用 xsd 实用程序自动生成的。
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = true)]
public partial class location
{
private string cityField;
private string countryField;
private string stateField;
private string textField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string city
{
get
{
return this.cityField;
}
set
{
this.cityField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string country
{
get
{
return this.countryField;
}
set
{
this.countryField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string state
{
get
{
return this.stateField;
}
set
{
this.stateField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string Text
{
get
{
return this.textField;
}
set
{
this.textField = value;
}
}
}
在我到达文件的这一部分之前一切正常:
<locations>
<location country="PARAGUAY" city="Ciudad del Este" state="Alto Parana" xsi:nil="true"/>
<location country="BRAZIL" city="Passo Fundo" state="Rio Grande do Sul" xsi:nil="true"/>
</locations>
作为stated in the MSDN,具有 xsi:nil="true" 的元素将被反序列化为空对象,完全丢失所有属性。在 C# 中,这转换为一个空对象。
有没有办法改变这种行为以反序列化三个属性?
提前感谢您的任何建议!
编辑 1:
这是关联的命名空间:
<records xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="structure.xsd">
(location is within here somewhere)
</records>
【问题讨论】:
-
xml 格式不正确。前缀
xsi未绑定到任何命名空间。 -
它有一个规范,我只是为了商业隐私而省略了它。我添加了一个修改版本。
-
并非如此。我正在尝试反序列化,而他正在尝试序列化。但是感谢您指出这一点。
-
@dbc 你是provvidential。我从那个答案中得到了建议,想出了一个解决方案。我一爬出这个泥池就会发布它。 >_
标签: c# .net xml deserialization xmlserializer