2013-09-25 42 views
1

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

XML文档(2,4)有错误。

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

字符串“假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。

回答

4

我还挺有与之一致:

<is64Bit>false fds</is64Bit> 

是不是一个有效的值:

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

你可以把它当作一个string

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

和处理它随后分开。

+0

这可能不是最好的例子。我只是在寻找一种方法来向用户提供更详细的错误。另一种情况可能是用户拼写其中一个元素错误或传递不存在的元素。我知道他们可以在他们身边进行验证,但我希望能够提供尽可能多的信息,以便我可以回复给用户。将实现我自己的序列化器是一个更好的选择来实现这一目标? – JStinebaugh

+0

@JStinebaugh在框架中提供了一个xsd-validating xml-reader,并提供了详细的输出。我会通过它来运行它。 –

相关问题