我将我的 XMLString 转换为 XMLSchema 如下代码(我正在使用带有任何元素的架构):
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.AllowXmlAttributes;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.Schemas.Add(null, XmlReader.Create(new StringReader(@"<xs:schema xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
<xs:element name=""bpElements"">
<xs:complexType>
<xs:sequence>
<xs:any />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>")));
try
{
// Create the XmlReader object.
XmlReader xmlrdr = XmlReader.Create(new StringReader("<root>" + ab + "</root>"), settings);
// Parse the file.
while (xmlrdr.Read()) ;
}
catch (XmlSchemaValidationException ex)
{
Console.WriteLine("The file could not read the value at XML format is not correct due to" + ex);
}
1)我的例外是根元素丢失。
为了避免上述错误:当我将根元素添加到我的架构时:(
参考:是否可以使用架构在 XML 文档中定义根元素?)
settings.Schemas.Add(null, XmlReader.Create(new StringReader(@"<xs:schema xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
<xs:element name=""root"" type=""RootElementType""/>
<xs:complexType name=""RootElementType"">
<xs:sequence>
<xs:any />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>")));
它会抛出错误:
The 'xs:schema' start tag on line 1 position 2 does not match the end tag of 'xs:element'. Line 8, position 63.
请让我知道如何解决。