使用带有命名空间http://mynamespace
的XML架构。如果验证了具有默认命名空间xmlns="http://mynamespace"
的错误XML文档,则会按预期抛出异常。如果有人更改了命名空间(http://Wrongnamespace
),则此错误的XML将通过验证。
以下是使用模式验证的单元测试。方法XSD_NotValid_2
无法正常运行:
[TestClass]
public class XSDTest
{
public System.Xml.XmlReaderSettings ReaderSettings
{
get
{
string sXSD = "<xsd:schema targetNamespace=\"http://mynamespace\" xmlns=\"http://mynamespace\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\">"
+ "<xsd:element name=\"Root\">"
+ "<xsd:complexType>"
+ "<xsd:sequence>"
+ "<xsd:element name=\"Child\" minOccurs=\"1\" maxOccurs=\"1\" />"
+ "</xsd:sequence>"
+ "</xsd:complexType>"
+ "</xsd:element>"
+ "</xsd:schema>";
System.Xml.Schema.XmlSchema schema = System.Xml.Schema.XmlSchema.Read(new System.IO.StringReader(sXSD)
, new System.Xml.Schema.ValidationEventHandler(OnValidationFail));
System.Xml.XmlReaderSettings readerSettings_Ret = new System.Xml.XmlReaderSettings();
readerSettings_Ret.ValidationType = System.Xml.ValidationType.Schema;
readerSettings_Ret.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(OnValidationFail);
readerSettings_Ret.Schemas.Add(schema);
return readerSettings_Ret;
}
}
private void OnValidationFail(object s, System.Xml.Schema.ValidationEventArgs e)
{
throw new OperationCanceledException("Validation error: " + e.Message);
}
[TestMethod]
public void XSD_Valid_Test()
{
// Valid elements and valid namespace
String sXML_Valid = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<Root xmlns=\"http://mynamespace\"><Child /></Root>";
System.Xml.XmlReader xmlReader_Valid =
System.Xml.XmlReader.Create(new System.IO.StringReader(sXML_Valid), this.ReaderSettings);
while (xmlReader_Valid.Read()) { } // no fail expected
}
[TestMethod]
[ExpectedException(typeof(OperationCanceledException))]
public void XSD_NotValid_1()
{
// No valid elements, while valid namespace
String sXML_NotValid_1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<BadRoot xmlns=\"http://mynamespace\"><Child /></BadRoot>";
System.Xml.XmlReader xmlReader_NoValid_1 =
System.Xml.XmlReader.Create(new System.IO.StringReader(sXML_NotValid_1), this.ReaderSettings);
while (xmlReader_NoValid_1.Read()) ;
}
[TestMethod]
[ExpectedException(typeof(OperationCanceledException))]
public void XSD_NotValid_2()
{
// No valid elements and no valid namespace
String sXML_NotValid_2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<Root xmlns=\"http://Wrongnamespace\"><NotValidChild /></Root>";
System.Xml.XmlReader xmlReader_NoValid_2 =
System.Xml.XmlReader.Create(new System.IO.StringReader(sXML_NotValid_2), this.ReaderSettings);
while (xmlReader_NoValid_2.Read()) ;
}
}
这是正常行为吗?如何强制正确的命名空间定位?
还有如何在XSD有额外Root
元素的情况下强制要求Root2
元素?
答案 0 :(得分:3)
如果启用架构验证警告,则会收到以下错误:
无法找到元素'http:// Wrongnamespace:Root'的架构信息。
使用
readerSettings_Ret.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
一些小事:
using
块中创建实现IDisposable的对象。事实上,我在单元测试中会说特别是,其中每个测试应该独立于其他测试,你要确保在开始下一个测试之前已经清理了一个测试。