我有一些 WCF 方法用于将信息从服务器应用程序传输到网站前端以用于绑定(bind)。我将结果作为 XElement 发送,它是包含我要绑定(bind)的数据的 XML 树的根。
我想创建一些测试来检查数据并确保它按预期出现。
我目前的想法是:每个返回 XElement 树的方法都有一个对应的架构 (.XSD) 文件。此文件作为嵌入式资源包含在包含我的 WCF 类的程序集中。
测试调用这些方法的方法并将结果与这些嵌入式模式进行比较。
这是个好主意吗?如果不是,我可以使用哪些其他方法来“保证”方法将返回哪种 XML?
如果是,您如何根据模式验证 XElement?我如何从嵌入它的程序集中获取该架构?
最佳答案
我说用 xsd 模式验证 xml 是个好主意。
如何使用加载的模式验证 XElement:
正如您在此示例中看到的,您需要首先验证 XDocument 以填充“后模式验证信息集”(可能有一种解决方案可以在不使用 XDOcument 上的 Validate 方法的情况下执行此操作,但我还没有找到一个):
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));
关于c# - 如何最好地从方法中测试 XML 的有效性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/117007/