2013-09-25 46 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,並提供了詳細的輸出。我會通過它來運行它。 –

相關問題