有谁知道我在c#中使用XSD验证XML时哪里出错了吗

时间:2021-08-09 15:04:39

Hi all i have my XML file as follows

大家好,我的XML文件如下。

Name of XML XMLFile2.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>

My XSD is as follows

我的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>

This is my code

这是我的代码

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");

I am getting the following errors

我得到了以下错误

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

Can any one tell where i went wrong.

谁能告诉我哪里出错了吗?

1 个解决方案

#1


5  

Your XSD is set to validate the "http://tempuri.org/Product.xsd" namespace, but your XML contains only elements from the "" namespace.

您的XSD被设置为验证“http://tempuri.org/Product.xsd”名称空间,但是您的XML只包含来自“”名称空间的元素。

You need to either (a) change the XML file to use the "http://tempuri.org/Product.xsd" namespace, or (b) change the XSD file to use the "" namespace, depending on your user requirements.

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

#1


5  

Your XSD is set to validate the "http://tempuri.org/Product.xsd" namespace, but your XML contains only elements from the "" namespace.

您的XSD被设置为验证“http://tempuri.org/Product.xsd”名称空间,但是您的XML只包含来自“”名称空间的元素。

You need to either (a) change the XML file to use the "http://tempuri.org/Product.xsd" namespace, or (b) change the XSD file to use the "" namespace, depending on your user requirements.

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