XmlSchemaValidationException:未声明'B'元素

Sta*_*lav 4 .net c# xml xsd

我正在使用XmlReader来验证Xml对抗Xsd.

当我验证这个xml

<?xml version="1.0" encoding="utf-8" ?>
<A><B>sdf</B></A>
Run Code Online (Sandbox Code Playgroud)

针对此架构:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="B" type="xs:string" />

<xs:element name="A">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="B"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

</xs:schema>
Run Code Online (Sandbox Code Playgroud)

验证没问题.

但是如果我添加命名空间:

<?xml version="1.0" encoding="utf-8" ?>
<A xmlns="myns"><B>sdf</B></A>
Run Code Online (Sandbox Code Playgroud)

和相应的架构:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="myns">

<xs:element name="B" type="xs:string" />

<xs:element name="A">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="B"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

</xs:schema>
Run Code Online (Sandbox Code Playgroud)

我接受System.Xml.Schema.XmlSchemaValidationException:未声明'B'元素.为什么会这样?我该如何添加命名空间?

tom*_*ern 5

您获得验证错误的原因是您的架构实际上是两个架构.您有两个根元素A和B.根元素不能隐式用作类型.您需要告诉XSD您要使用来自另一个模式的类型(使用导入),或者将这些类型设置为模式的本地类型(使用complexType定义).

示例:将B提取到其自己的架构中.它不能共享相同的命名空间:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="myns2">
  <xs:element name="B" type="xs:string" />
</xs:schema>
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用导入从A类型引用B:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="myns" xmlns:myns2="myns2">

  <xs:import namespace="myns2" />

  <xs:element name="A">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="myns2:B" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>
Run Code Online (Sandbox Code Playgroud)

这允许您拥有以下有效的XML实例:

<?xml version="1.0" encoding="utf-8" ?>
<A xmlns="myns">
  <B xmlns="myns2">sdf</B>
</A>
Run Code Online (Sandbox Code Playgroud)

您能够验证类型的非命名空间版本的原因是因为为了成为有效的XML,需要做两件事情:

  • 格式良好的XML
  • 必须符合任何引用的模式类型

在非命名空间的XML文件中,根据定义,没有对任何模式类型的引用,因此文档是有效的XML.