gpt4 book ai didi

c# - 使用强类型 XSD 反序列化 XML 文档时出错

转载 作者:数据小太阳 更新时间:2023-10-29 02:59:55 37 4
gpt4 key购买 nike

在尝试使用 XmlSerializer.Deserialize() 方法反序列化特定 XML 文档时,我遇到了一个非常烦人的问题。

基本上,我有一个带有 double 类型元素的强类型 XSD。当尝试反序列化特定 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(或任何其他类型)?理想情况下,我想避免实现 ISerializable,因为我真的不想把一天剩下的时间都花在 hell 的燃烧坑里(即为大约一百个类实现 ISerializable)。

干杯!让-米歇尔

最佳答案

查看有关 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 值。无论如何,这似乎正是我要找的。

非常感谢塞巴斯蒂安!

关于c# - 使用强类型 XSD 反序列化 XML 文档时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/461584/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com