在尝试使用 XmlSerializer.Deserialize() 方法反序列化特定 XML 文档时,我遇到了一个相当烦人的问题。
基本上,我有一个强类型 XSD,其中有一个 double 类型的元素。当尝试反序列化特定 XML 文档的元素时,我收到常见的“System.FormatException:输入字符串的格式不正确”。异常,因为在该特定文档中,该元素没有值。
这里有一些代码供你们这些 Nerd 使用。
示例 XML 文档:
<TrackInfo>
<Name>Barcelona</Name>
<Length>4591</Length>
<AverageSpeed />
</TrackInfo>
XSD:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="TrackInfo">
<xs:complexType>
<xs:sequence>
<xs:element name="Name" type="xs:string" />
<xs:element name="Length" type="xs:double" default="0.0" />
<xs:element name="AverageSpeed" type="xs:double" default="0.0" />
</xs:sequence>
</xs:complexType>
</xs:element>
TrackInfo 类:
[Serializable]
public class TrackInfo
{
private string name = string.Empty;
private double length = 0.0;
private double averageSpeed = 0.0;
[XmlElement]
public string Name
{ ... }
[XmlElement]
public double Length
{ ... }
[XmlElement]
public double AverageSpeed
{ ... }
}
示例反序列化代码:
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load("TrackInfo.xml");
// Deserialise XML string into TrackInfo object
byte[] buffer = ASCIIEncoding.UTF8.GetBytes(xmlDocument.InnerXml);
MemoryStream stream = new MemoryStream(buffer);
System.Xml.XmlReader reader = new System.Xml.XmlTextReader(stream);
XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(typeof(TrackInfo));
TrackInfo trackInfo = (TrackInfo)xSerializer.Deserialize(reader);
我知道反序列化异常来自于空字符串无法转换为 double 值。我还知道默认值未分配给 AverageSpeed,因为实际上空字符串是完全可接受的值。
如果在 XML 文档中找到空字符串值,是否有一种简单的方法可以在反序列化时将 double 值默认为 0.0(或任何其他类型)? 理想情况下,我希望避免实现 ISerialized,因为我真的不想将这一天剩下的时间花在 hell 的燃烧坑中(即为大约一百个类实现 ISerialized)。
干杯! 让-米歇尔
最佳答案
查看有关 DefaultValueAttribute 的 MSDN 文档: http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx
Note: A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.
我认为字段初始化始终优先于 DefaultValueAttribute 值。无论如何,这似乎正是我所寻找的。p>
非常感谢你塞巴斯蒂安!
关于c# - 使用强类型 XSD 反序列化 XML 文档时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/461584/