使用XDocument或XmlReader的XML验证无效

时间:2019-04-16 07:53:44

标签: c# xml xsd xsd-validation

我尝试针对xsd验证xml文件。

我找到了这两个版本来实现:

我都尝试过,但都无法正常工作。

我使用的简单代码是:

using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;

public class Test
{
    #region Xsd
    public const string Xsd = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<schema xmlns=""http://www.w3.org/2001/XMLSchema"" targetNamespace=""http://www.sample.de/Testing"" xmlns:tns=""http://www.sample.de/Testing"" elementFormDefault=""qualified"">
    <element name=""root"">
        <complexType>
            <sequence>
                <element name=""Version"">
                    <simpleType>
                        <restriction base=""string"">
                            <enumeration value=""V1""></enumeration>
                        </restriction>
                    </simpleType>
                </element>
            </sequence>
        </complexType>
    </element>
</schema>";
    #endregion

    public const string InvalidXml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<IdentificationInData xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/Toolkit.Common.Data"">
  <Args xmlns=""http://schemas.datacontract.org/2004/07/Toolkit.Common.Data"">/NoiseDuration=Seconds2 /Philosophy=Distance /SamplingRate=10</Args>
</IdentificationInData>";

    public static void Main()
    {
        Console.WriteLine(IsValidUsingXDocument(null));
        Console.WriteLine(IsValidUsingXDocument("http://www.sample.de/Testing"));

        Console.WriteLine(IsValidUsingXmlReader(null));
        Console.WriteLine(IsValidUsingXmlReader("http://www.sample.de/Testing"));
    }

    public static bool IsValidUsingXDocument(string schemaNamespace)
    {
        // https://docs.microsoft.com/en-us/dotnet/api/system.xml.schema.extensions.validate?redirectedfrom=MSDN&view=netframework-4.7.2#System_Xml_Schema_Extensions_Validate_System_Xml_Linq_XDocument_System_Xml_Schema_XmlSchemaSet_System_Xml_Schema_ValidationEventHandler_

        using (var xsdContentReader = new StringReader(Xsd))
        using (var xsdReader = XmlReader.Create(xsdContentReader))
        using (var databaseContentReader = new StringReader(InvalidXml))
        {
            var schemas = new XmlSchemaSet();
            schemas.Add(schemaNamespace, xsdReader);

            try
            {
                var result = true;

                var doc = XDocument.Load(databaseContentReader);
                doc.Validate(schemas, (_, __) => result = false);
                return result;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }

    public static bool IsValidUsingXmlReader(string schemaNamespace)
    {
        // https://docs.microsoft.com/en-us/dotnet/api/system.xml.schema.validationeventargs.severity?redirectedfrom=MSDN&view=netframework-4.7.2#System_Xml_Schema_ValidationEventArgs_Severity

        using (var xsdContentReader = new StringReader(Xsd))
        using (var xsdReader = XmlReader.Create(xsdContentReader))
        {
            var result = true;

            var settings = new XmlReaderSettings();
            settings.Schemas.Add(schemaNamespace, xsdReader);
            settings.ValidationEventHandler += (_, __) => result = false;
            settings.ValidationType = ValidationType.Schema;

            using (var databaseContentReader = new StringReader(InvalidXml))
            using (var validatingReader = XmlReader.Create(databaseContentReader, settings))
            {
                while (validatingReader.Read())
                {
                }
            }

            return result;
        }
    }
}

此代码可在以下位置运行以进行测试:https://dotnetfiddle.net/leNBW8

问题是xsd和xml完全不同,验证应该失败-但没有成功。甚至根标签都不匹配。

我在做什么错了?

0 个答案:

没有答案