【问题标题】:XML validate using XSDs with imports and includes in .net coreXML 使用带有导入的 XSD 进行验证,并包含在 .net 核心中
【发布时间】:2020-01-16 20:25:17
【问题描述】:

我想通过包含和导入来针对 xsds 验证 XML 文档,而没有包含和导入此代码工作。 这些是用于验证 xml 的 4 个 xsd。

Main.xsd

<?xml version="1.0" encoding="utf-8"?>
<xs:schema  xmlns:ord="http://NamespaceTest.com/OrderTypes"
xmlns:pur="http://NamespaceTest.com/Purchase"
xmlns:cmn="http://NamespaceTest.com/CommonTypes"
xmlns:cust="http://NamespaceTest.com/CustomerTypes"
targetNamespace="http://NamespaceTest.com/Purchase"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:import  schemaLocation="CommonTypes.xsd"
namespace="http://NamespaceTest.com/CommonTypes" />
<xs:import  schemaLocation="CustomerTypes.xsd"
namespace="http://NamespaceTest.com/CustomerTypes" />
<xs:import  schemaLocation="OrderTypes.xsd"
namespace="http://NamespaceTest.com/OrderTypes" />
<xs:element  name="Purchase">
<xs:complexType>
<xs:sequence>
<xs:element  name="OrderDetail"  type="ord:OrderType" />
<xs:element  name="PaymentMethod"  type="cmn:PaymentMethodType" />
<xs:element  ref="pur:CustomerDetails" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element  name="CustomerDetails"  type="cust:CustomerType" />
</xs:schema>

CommonTypes.xsd

<?xml version="1.0" encoding="utf-8"?>
<xs:schema  targetNamespace="http://NamespaceTest.com/CommonTypes"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:complexType  name="AddressType">
<xs:sequence>
<xs:element  name="Line1"  type="xs:string" />
<xs:element  name="Line2"  type="xs:string" />
</xs:sequence>
</xs:complexType>
<xs:simpleType  name="PriceType">
<xs:restriction  base="xs:decimal">
<xs:fractionDigits  value="2" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType  name="PaymentMethodType">
<xs:restriction  base="xs:string">
<xs:enumeration  value="VISA" />
<xs:enumeration  value="MasterCard" />
<xs:enumeration  value="Cash" />
<xs:enumeration  value="AMEX" />
</xs:restriction>
</xs:simpleType>
</xs:schema>

CustomerTypes.xsd

<?xml version="1.0" encoding="utf-8"?>
<xs:schema  xmlns:cmn="http://NamespaceTest.com/CommonTypes"
targetNamespace="http://NamespaceTest.com/CustomerTypes"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:import  schemaLocation="CommonTypes.xsd"
namespace="http://NamespaceTest.com/CommonTypes" />
<xs:complexType  name="CustomerType">
<xs:sequence>
<xs:element  name="Name"  type="xs:string" />
<xs:element  name="DeliveryAddress"  type="cmn:AddressType" />
<xs:element  name="BillingAddress"  type="cmn:AddressType" />
</xs:sequence>
</xs:complexType>
</xs:schema>

OrderTypes.xsd

<?xml version="1.0" encoding="utf-8"?>
<xs:schema  xmlns:cmn="http://NamespaceTest.com/CommonTypes"
targetNamespace="http://NamespaceTest.com/OrderTypes"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:import  schemaLocation="CommonTypes.xsd"
namespace="http://NamespaceTest.com/CommonTypes" />
<xs:complexType  name="OrderType">
<xs:sequence>
<xs:element  maxOccurs="unbounded"  name="Item">
<xs:complexType>
<xs:sequence>
<xs:element  name="ProductName"  type="xs:string" />
<xs:element  name="Quantity"  type="xs:int" />
<xs:element  name="UnitPrice"  type="cmn:PriceType" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:schema>

这是要验证的xml

<?xml version="1.0" encoding="utf-8"?>
  <CustomerDetails>
    <Name>Peter James</Name>
    <DeliveryAddress>
      <Line1>141 Saint Carmen</Line1>
      <Line2>Zeel Street, MA, US</Line2>
    </DeliveryAddress>
    <BillingAddress>
      <Line1>142 Saint Carmen</Line1>
      <Line2>Zeel Street, MA, US</Line2>
    </BillingAddress>
  </CustomerDetails>

我在验证 xml 时遇到了这个错误

  System.Xml.Schema.XmlSchemaException: 'Type 'http://NamespaceTest.com/CustomerTypes:CustomerType' is not declared.'

代码 sn-p 用于验证

using System;
using System.Xml;
using System.Xml.Schema;

namespace ConsoleApp3
{
    class XmlValidatorTest
    {
        static void Main()
        {
            Console.WriteLine("Start XML Validator.....");

            // Create the XmlSchemaSet class.
            XmlSchemaSet sc = new XmlSchemaSet();

            // Add the schema to the collection.
            sc.Add("http://NamespaceTest.com/Purchase", "test_xml_schemas/Main.xsd");
            sc.Compile();

            foreach (XmlSchema schema in sc.Schemas())
            {
                Console.WriteLine(schema.TargetNamespace);
            }

            // Set the validation settings.
            XmlReaderSettings setting = new XmlReaderSettings();
            setting.Schemas.Add(sc);
            setting.ValidationType = ValidationType.Schema;
            setting.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
            setting.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;

            setting.ValidationEventHandler += new ValidationEventHandler(Handler);

            using (XmlReader validationReader = XmlReader.Create("test_xmls/CustomerDetails01.xml", setting))
            {
                while (validationReader.Read())
                {
                    /* do nothing for while */
                }
            }

            Console.ReadLine();
        }

        // Display any validation errors.
        private static void Handler(object sender, ValidationEventArgs e)
        {
            if (e.Severity == XmlSeverityType.Error ||
                e.Severity == XmlSeverityType.Warning)
            {
                Console.WriteLine(String.Format("Line: {0}, Position: {1} '{2}'",
                    e.Exception.LineNumber, e.Exception.LinePosition, e.Exception.Message));

            }
        }
    }
}

Validating xml against an xsd that has include and import in c# 我试试这个也有这个错误:

System.Xml.Schema.XmlSchemaException
  HResult=0x80131941
  Message=The targetNamespace 'http://NamespaceTest.com/Purchase' of included/redefined schema should be the same as the targetNamespace '' of the including schema.
  Source=System.Private.Xml
  StackTrace:
   at System.Xml.Schema.XmlSchemaSet.InternalValidationCallback(Object sender, ValidationEventArgs e)
   at System.Xml.Schema.BaseProcessor.SendValidationEvent(XmlSchemaException e, XmlSeverityType severity)
   at System.Xml.Schema.BaseProcessor.SendValidationEvent(String code, String msg1, String msg2, XmlSchemaObject source)
   at System.Xml.Schema.Preprocessor.Preprocess(XmlSchema schema, String targetNamespace, ArrayList imports)
   at System.Xml.Schema.Preprocessor.Execute(XmlSchema schema, String targetNamespace, Boolean loadExternals)
   at System.Xml.Schema.XmlSchemaSet.PreprocessSchema(XmlSchema& schema, String targetNamespace)
   at System.Xml.Schema.XmlSchemaSet.Add(String targetNamespace, XmlSchema schema)
   at System.Xml.Schema.XmlSchemaSet.Add(XmlSchema schema)
   at ConsoleApp3.XmlValidator.Main() in D:\App\ConsoleApp3\ConsoleApp3\XmlValidator.cs:line 29

【问题讨论】:

    标签: .net xml xsd


    【解决方案1】:

    我有类似的问题,我通过添加解决了它

    sc.XmlResolver = new XmlUrlResolver();
    

    在将架构添加到集合之前添加到我的代码

    XmlSchemaSet sc = new XmlSchemaSet();
    
    // Add url resolver to fix the issue
    sc.XmlResolver = new XmlUrlResolver();
    // Add the schema to the collection.
    sc.Add("http://NamespaceTest.com/Purchase", "test_xml_schemas/Main.xsd");
    sc.Compile();
    

    我关注了different behavior for Full Framework and .NET Core for xml schema compilation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-21
      • 2012-04-13
      • 1970-01-01
      • 1970-01-01
      • 2012-06-11
      • 2014-03-27
      相关资源
      最近更新 更多