【问题标题】:Provide element name for Xml Serialization Error为 Xml 序列化错误提供元素名称
【发布时间】:2013-09-25 13:54:29
【问题描述】:

我试图弄清楚如何提供自定义错误消息或至少为我的 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 的方法。

【问题讨论】:

    标签: c# xml asp.net-mvc asp.net-web-api xml-serialization


    【解决方案1】:

    我不得不同意:

    <is64Bit>false fds</is64Bit>
    

    不是以下的有效值:

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

    您可以将其视为string

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

    之后单独处理。

    【讨论】:

    • 这可能不是最好的例子。我只是在寻找一种方法来向用户提供更详细的错误。另一种情况可能是用户拼写错误的元素之一或传递了一个不存在的元素。我知道他们可以在他们这边进行验证,但我希望能够提供尽可能多的信息,我也可以返回给用户。实现我自己的序列化器会是实现这一目标的更好选择吗?
    • @JStinebaugh 框架中提供了一个 xsd-validating xml-reader 并提供详细的输出。我会通过它运行它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    • 2017-01-27
    • 1970-01-01
    相关资源
    最近更新 更多