【问题标题】:Can any one tell where i went wrong in validating an XML with XSD in C#谁能告诉我在 C# 中使用 XSD 验证 XML 时哪里出错了
【发布时间】:2011-12-12 13:00:25
【问题描述】:

大家好,我的XML 文件如下

XML的名称XMLFile2.xml

<?xml version="1.0"?>
<Product ProductID="123"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="Product.xsd">
<ProductName>XYZ</ProductName>
</Product>

我的XSD如下

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="Product"
targetNamespace="http://tempuri.org/Product.xsd"
elementFormDefault="qualified"
xmlns="http://tempuri.org/Product.xsd"
xmlns:mstns="http://tempuri.org/Product.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Product">
<xs:complexType>
  <xs:sequence>
    <xs:element name="ProductName" type="xs:string"></xs:element>
  </xs:sequence>
  <xs:attribute name="ProductID" type="xs:int" use="required"/>
</xs:complexType>
 </xs:element>

这是我的代码

string strPath = Server.MapPath("XMLFile2.xml");
XmlTextReader r = new XmlTextReader(strPath);
XmlValidatingReader v = new XmlValidatingReader(r);
v.ValidationType = ValidationType.Schema;
v.ValidationEventHandler +=
new ValidationEventHandler(MyValidationEventHandler);
while (v.Read())
    {

    }
v.Close();

    if (isValid)
        Response.Write("Document is valid");
    else
        Response.Write("Document is invalid");

我收到以下错误

Validation event
The targetNamespace parameter '' should be the same value as the targetNamespace 'http://tempuri.org/Product.xsd' of the schema.Validation event
The 'Product' element is not declared.Validation event
Could not find schema information for the attribute 'ProductID'.Validation event
The 'ProductName' element is not declared.Document is invalid

谁能告诉我哪里出错了。

【问题讨论】:

    标签: c# .net xml xsd


    【解决方案1】:

    您的 XSD 设置为验证 "http://tempuri.org/Product.xsd" 命名空间,但您的 XML 仅包含来自 "" 命名空间的元素。

    您需要 (a) 更改 XML 文件以使用 "http://tempuri.org/Product.xsd" 命名空间,或 (b) 更改 XSD 文件以使用 "" 命名空间,具体取决于您的用户要求。

    【讨论】:

    • 您的 XML 文件根元素没有 xmlns 属性,因此所有元素都属于空命名空间 ("")。相比之下,您的 XSD 文件具有指定特定命名空间的 targetNamespace 属性。
    • @User - 您的 XML 没有默认命名空间。
    • 嗯,谁能告诉我现在想做什么改变
    猜你喜欢
    • 1970-01-01
    • 2021-09-07
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    相关资源
    最近更新 更多