2008-09-22 42 views
5

我有一些WCF方法用於將信息從服務器應用程序傳輸到網站前端以用於綁定。我將結果作爲XElement發送,該XElement是包含要綁定的數據的XML樹的根。如何最好地從方法測試XML的有效性?

我想創建一些測試來檢查數據並確保它符合預期。

我現在的想法是這樣的:返回XElement樹的每個方法都有一個對應的模式(.XSD)文件。該文件包含在包含我的WCF類作爲嵌入式資源的程序集中。

測試調用這些方法的方法,並將結果與​​這些嵌入式模式進行比較。

這是個好主意嗎?如果沒有,我還可以使用其他什麼方式來提供「保證」方法將返回哪種XML?

如果是這樣,您如何根據模式驗證XElement?我如何從嵌入的程序集中獲取該模式?

回答

11

我說使用xsd模式驗證xml是個好主意。

如何使用加載的模式驗證XElement: 正如您在本例中看到的,您需要首先驗證XDocument才能填充「模式驗證後信息集」(可能有解決方案無需執行此操作使用上的XDocument,但IM的驗證方法沒有找到一個):

String xsd = 
@"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'> 
    <xsd:element name='root'> 
    <xsd:complexType> 
    <xsd:sequence> 
     <xsd:element name='child1' minOccurs='1' maxOccurs='1'> 
     <xsd:complexType> 
     <xsd:sequence> 
     <xsd:element name='grandchild1' minOccurs='1' maxOccurs='1'/> 
     <xsd:element name='grandchild2' minOccurs='1' maxOccurs='2'/> 
     </xsd:sequence> 
     </xsd:complexType> 
     </xsd:element> 
    </xsd:sequence> 
    </xsd:complexType> 
    </xsd:element> 
    </xsd:schema>"; 
String xml = @"<?xml version='1.0'?> 
<root> 
    <child1> 
     <grandchild1>alpha</grandchild1> 
     <grandchild2>beta</grandchild2> 
    </child1> 
</root>"; 
XmlSchemaSet schemas = new XmlSchemaSet(); 
schemas.Add("", XmlReader.Create(new StringReader(xsd))); 
XDocument doc = XDocument.Load(XmlReader.Create(new StringReader(xml))); 
Boolean errors = false; 
doc.Validate(schemas, (sender, e) => 
{ 
    Console.WriteLine(e.Message); 
    errors = true; 
}, true); 
errors = false; 
XElement child = doc.Element("root").Element("child1"); 
child.Validate(child.GetSchemaInfo().SchemaElement, schemas, (sender, e) => 
{ 
    Console.WriteLine(e.Message); 
    errors = true; 
}); 

如何從裝配讀取嵌入的模式,並將其添加到XmlSchemaSet中:

Assembly assembly = Assembly.GetExecutingAssembly(); 
// you can use reflector to get the full namespace of your embedded resource here 
Stream stream = assembly.GetManifestResourceStream("AssemblyRootNamespace.Resources.XMLSchema.xsd"); 
XmlSchemaSet schemas = new XmlSchemaSet(); 
schemas.Add(null, XmlReader.Create(stream)); 
+0

element.GetSchemaInfo()返回null。 – Will 2008-09-23 13:37:19

4

如果」回覆 做一些輕量級的工作和XSD是矯枉過正的,也可能強烈地考慮輸入你的XML數據。例如,我在XElement派生的項目中有許多類。一個是ExceptionXElement,另一個是HttpHeaderXElement等。在他們中,我從XElement繼承並添加Parse和TryParse方法,這些方法使用包含XML數據的字符串來創建實例。如果TryParse()返回false,則該字符串不符合我期望的XML數據(根元素名稱錯誤,缺少子元素等)。

例如:

public class MyXElement : XElement 
{ 

    public MyXElement(XElement element) 
     : base(element) 
    { } 

    public static bool TryParse(string xml, out MyXElement myElement) 
    { 
     XElement xmlAsXElement; 

     try 
     { 
      xmlAsXElement = XElement.Parse(xml); 
     } 
     catch (XmlException) 
     { 
      myElement = null; 
      return false; 
     } 

     // Use LINQ to check if xmlAsElement has correct nodes... 
    } 
相關問題