简体   繁体   English

C#反序列化和使用XmlReader.Create针对XSD验证XML文件不起作用

[英]C# Deserializing, and validating an XML file against an XSD using XmlReader.Create isn't working

I am using Visual Studio 2015. I apologize for the poorly named "firstName" element. 我正在使用Visual Studio2015。对于名称不正确的“ firstName”元素,我深表歉意。 It should have been "fullName", but since I already generated the class for the schema, and this is just for my own learning, I left it as is. 它本来应该是“ fullName”,但是由于我已经为模式生成了类,并且这只是出于我自己的学习,所以我将其保留为原样。 I have an XML schema here: 我在这里有一个XML模式:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="address-schema"
targetNamespace="http://tempuri.org/address-schema.xsd"
elementFormDefault="qualified"
attributeFormDefault="qualified"
xmlns:addr="http://tempuri.org/address-schema.xsd"
xmlns:mstns="http://tempuri.org/address-schema.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
  <xs:element name="address">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="firstName">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="first" type="addr:nameComponent"/>
              <xs:element name="middle" type="addr:nameComponent" minOccurs="0"/>
              <xs:element name="last" type="addr:nameComponent"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

  <xs:complexType name="nameComponent">
    <xs:simpleContent>
      <xs:extension base="xs:string"/>
    </xs:simpleContent>
  </xs:complexType>

</xs:schema>

And an XML file that I think conforms to the schema: 我认为符合该架构的XML文件:

<?xml version="1.0" encoding="utf-8" ?>
<addr:address xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
          xsi:schemaLocation="http://tempuri.org/address-schema.xsd address-schema.xsd" 
          xmlns:addr="http://tempuri.org/address-schema.xsd">
  <addr:firstName>
    <addr:first>Some</addr:first>
    <addr:middle>Bodys</addr:middle>
    <addr:last>Name</addr:last>
  </addr:firstName>
</addr:address>

And the code that is attempting to validate the XML is here (note that the "address" class that the XML file is getting deserialized into is an auto generated class from xsd.exe): 这里是尝试验证XML的代码(请注意,XML文件被反序列化为“ address”类是从xsd.exe自动生成的类):

address address;
var xmlSchemaSerializer = new XmlSerializer(typeof(XmlSchema));
var addressXmlSerializer = new XmlSerializer(typeof(address));

var schemas = new XmlSchemaSet();
XmlSchema schema;
using (var xsdStream = File.OpenRead("address-schema.xsd"))
{
    schema = (XmlSchema)xmlSchemaSerializer.Deserialize(xsdStream);
}
schemas.Add(schema);
var settings = new XmlReaderSettings
{
    Schemas = schemas,
    ValidationType = ValidationType.Schema,
    ValidationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ProcessSchemaLocation
};
settings.ValidationEventHandler += (sender, arguments) =>
{
    throw new XmlSchemaValidationException(arguments.Message);
};

using(Stream addressXmlStream = File.OpenRead("address-doc.xml"))
using (XmlReader reader = XmlReader.Create(addressXmlStream, settings))
{
    address = (address)addressXmlSerializer.Deserialize(reader);
}
Console.WriteLine(address.firstName.first.Value == "Some" ? "Success!" : "Fail");
Console.ReadKey();

The exception ('System.Xml.Schema.XmlSchemaValidationException'The global element ' http://tempuri.org/address-schema.xsd:address ' has already been declared.) is thrown in the ValidationEventHandler. 在ValidationEventHandler中引发了异常(已声明'System.Xml.Schema.XmlSchemaValidationException'全局元素' http://tempuri.org/address-schema.xsd:address '。)。 Any help or suggestions would be appreciated. 任何帮助或建议,将不胜感激。 Thanks in advance! 提前致谢!

The cause of your exception is that your document has a schema location hint that loads the schema, but you've already loaded it. 产生异常的原因是您的文档具有一个架构位置提示,该提示已加载架构,但是您已经加载了它。

Either don't pre-load the schema or remove the xsi:schemaLocation attribute from your document. 不要预加载模式,也不要从文档中删除xsi:schemaLocation属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM