我有这个XML文件
<bookstore>
<test>
<test2/>
</test>
</bookstore>和这个XSD模式
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="bookstore" type="bookstoreType"/>
<xsd:complexType name="bookstoreType">
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="test" type="xsd:anyType" />
</xsd:sequence>
</xsd:complexType>
</xsd:schema>我打算从C#代码中验证xml文件。有一种验证XML文件的方法:
// validate xml
private void ValidateXml()
{
_isValid = true;
// Get namespace from xml file
var defaultNamespace = XDocument.Load(XmlFileName).Root.GetDefaultNamespace().NamespaceName;
// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.Schemas.Add(defaultNamespace, XsdFileName);
settings.ValidationEventHandler += OnValidationEventHandler;
// Create the XmlReader object.
using(XmlReader reader = XmlReader.Create(XmlFileName, settings))
{
// Parse the file.
while (reader.Read()) ;
}
}
private void OnValidationEventHandler(object s, ValidationEventArgs e)
{
if (_isValid) _isValid = false;
if (e.Severity == XmlSeverityType.Warning)
MessageBox.Show("Warning: " + e.Message);
else
MessageBox.Show("Validation Error: " + e.Message);
}我知道,这个XML文件是有效的。但是我的代码修改了这个错误:
Validation Error: Could not find schema information for the element 'test2'我的错误在哪里?
谢谢!
发布于 2012-05-14 16:53:11
更新:我假设您的代码与您列出的错误相匹配(我已经在.NET 3.5SP1上尝试过您的代码,并且无法再现您的行为)。下面的解决方法应该是可以肯定的(您得到的错误与流程内容子句strict一致,而不是lax)。
将<xsd:element name="test" type="xsd:anyType" />替换为允许xsd:any的复杂内容,如下所示:
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="bookstore" type="bookstoreType"/>
<xsd:complexType name="bookstoreType">
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="test">
<xsd:complexType>
<xsd:sequence>
<xsd:any minOccurs="0" maxOccurs="unbounded" processContents="lax"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:schema> “松懈”仍然会产生一条消息;如果您希望该消息消失,可以使用“跳过”。无论如何,xsd:any中的skip和lax都能满足您的需要。
https://stackoverflow.com/questions/10587520
复制相似问题