为 Xml 序列化错误提供元素名称

本文关键字:元素 Xml 序列化 错误 | 更新日期: 2023-09-27 18:32:42

我正在尝试弄清楚如何提供自定义错误消息或至少为我的 Web API 的 XML 帖子指定元素名称。 目前,我得到的模型状态错误是

XML 文档 (2, 4) 中存在错误。

此错误的内部异常提供了更多信息:

字符串"false fds"不是有效的布尔值。

我希望能够向用户返回更具体的内容,说明包含无效值的元素,而不是让他们搜索其 XML 以确定该值存在的位置。

这是我发布的 XML:

<?xml version='1.0'?>
<checkin>
    <checkinType>1</checkinType>
    <server>server1</server>
    <notes>New Checkin</notes>
    <productCheckins>
        <ihsCheckin>
            <vendor>IBM</vendor>
            <make>HTTP Server</make>
            <model></model>
            <version>8.5.5.0</version>
            <installLocation>/opt/IBM</installLocation>
            <is64Bit>false fds</is64Bit>
        </ihsCheckin>
</productCheckins>
</checkin>

以下是我尝试转换为的类:

[XmlRoot("checkin")]
public class Checkin
{
    [XmlElement("checkinTime")]
    public DateTime CheckinTime { get; set; }
    [XmlElement("checkType")]
    public int CheckinType { get; set; }
    [XmlElement("notes")]
    public string Notes { get; set; }
    [XmlElement("server")]
    public string Server { get; set; }
    [XmlArray("productCheckins")]
    [XmlArrayItem("wasCheckin", typeof(WASCheckin))]
    [XmlArrayItem("ihsCheckin", typeof(IHSCheckin))]
    public List<ProductCheckin> ProductCheckins { get; set; }
}
public class ProductCheckin
{
    [XmlElement("vendor")]
    public string Vendor { get; set; }
    [XmlElement("make")]
    public string Make { get; set; }
    [XmlElement("model")]
    public string Model { get; set; }
    [XmlElement("version")]
    public string Version { get; set; }
    [XmlElement("installLocation")]
    public string InstallLocation { get; set; }
    [XmlElement("is64Bit")]
    public bool Is64Bit { get; set; }
}
基本上,我

只想说,该错误与is64Bit元素有关,但是除了手动解析XML之外,我还没有看到一种方法可以做到这一点。

为 Xml 序列化错误提供元素名称

我有点同意它:

<is64Bit>false fds</is64Bit>

不是以下项的有效值:

[XmlElement("is64Bit")]
public bool Is64Bit { get; set; }

您可以将其视为string

[XmlElement("is64Bit")]
public string Is64Bit { get; set; }

之后单独处理。

相关文章: