我正在尝试使用 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>
最佳答案
如果您只是想丢弃 xsi:nil
属性,请设置 XmlElementAttribute.IsNullable = false
在引用 location
的包含类中的属性的 [XmlElement]
属性中。
例如。如果你有
[System.Xml.Serialization.XmlRootAttribute("locations", Namespace = "")]
public class LocationList
{
[XmlElement("location", IsNullable = true)]
public List<location> Locations { get; set; }
}
手动更改为:
[System.Xml.Serialization.XmlRootAttribute("locations", Namespace = "")]
public class LocationList
{
[XmlElement("location", IsNullable = false)]
public List<location> Locations { get; set; }
}
如果您想绑定(bind)到xsi:nil
的值,同时绑定(bind)到其他属性值,除了设置IsNullable = false
,您可以按照 Can I have null attribute and other attribute at the same tag in XML created by XSD C# generated class? 中所示的行添加手动属性:
public partial class location
{
bool nil;
[XmlAttribute("nil", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public bool Nil
{
get
{
return nil;
}
set
{
nil = value;
}
}
public bool ShouldSerializeNil() { return nil == true; }
}
样本 fiddle .
您还可以对 XML 进行预处理和后处理,以重命名 xsi:nil
属性,如 this answer 中所建议的那样.
关于c# - 使用 xsi :nil ="true" in C# 反序列化 XML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38018419/