2011-06-28 71 views
0

我的函數在XDocument構造函數上爆炸了。說非空白字符是不允許的。如何根據XSD文件驗證XML字符串?

public static bool ValidateXML(string xml, string xsd) 
{ 
    StringBuilder sb = new StringBuilder(); 
    bool blnReturn = true; 
    bool errors = false; 
    XmlSchemaSet schemas = new XmlSchemaSet(); 
    schemas.Add("", XmlReader.Create(new StringReader(xsd))); 
    XDocument xmlDoc = new XDocument(XmlReader.Create(new StringReader(xml))); 

    //validate the XML text against the XSD 
    xmlDoc.Validate(schemas, (o, e) => 
    { 
      sb.AppendLine(e.Message); 
      errors = true; 
    }); 

    //if there are errors, display them and return false 
    if (errors) 
    { 
     MessageBox.Show("XML did not parse cleanly. Please fix the following errors.\n\n" + sb.ToString(), "XML Parsing Results"); 
     blnReturn = false; 
    } 
    else 
    { 
     MessageBox.Show("XML Parsed cleanly. Saving to file.", "XML Parsing Results"); 
    } 

    return blnReturn; 
} 

回答

0

我看不出有什麼問題的代碼。很可能你的xml字符串是無效的。非空白字符錯誤表示您的xml元素之間有「文字」字符。例如:

<blah>This text is okay</blah>This text isn't 
<blah>More text</blah> 
+0

我通過粘貼到W3Schools XML驗證器中,檢查了插入到函數中的文本。它乾淨地驗證。難道這是因爲它從一個RTF控件拉出來,並且可能有不可見的格式化字符? –

+1

我想你可能已經回答了你自己的問題。創建一個單元測試,直接傳入你的「有效」xml,看看它是否有效。 – theoretical