C# 为什么我的 XML 验证针对其架构失败?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1007881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:23:16  来源:igfitidea点击:

Why is my XML validation failing against its schema?

c#xmlvalidationxsd

提问by Keith Sirmons

I need to validate a XML file against a schema. The XML file is being generated in code and before I save it I need to validate it to be correct.

我需要根据架构验证 XML 文件。XML 文件是在代码中生成的,在我保存它之前,我需要验证它是否正确。

I have stripped the problem down to its barest elements but am having an issue.

我已将问题分解为最基本的元素,但遇到了问题。

XML:

XML:

<?xml version="1.0" encoding="utf-16"?>
<MRIDSupportingData xmlns="urn:GenericLabData">
  <MRIDNumber>MRIDDemo</MRIDNumber>
  <CrewMemberIdentifier>1234</CrewMemberIdentifier>
  <PrescribedTestDate>1/1/2005</PrescribedTestDate>
</MRIDSupportingData>

Schema:

架构:

<?xml version="1.0" encoding="utf-16"?>
<xs:schema xmlns="urn:GenericLabData" targetNamespace="urn:GenericLabData" 
   xmlns:xs="http://www.w3.org/2001/XMLSchema">

   <xs:element name="MRIDSupportingData">
   <xs:complexType> 
      <xs:sequence>
        <xs:element name="MRIDNumber" type="xs:string" /> 
        <xs:element minOccurs="1" name="CrewMemberIdentifier" type="xs:string" />
      </xs:sequence>
   </xs:complexType>
  </xs:element>
</xs:schema>  

ValidationCode: (This code is from a simple app I wrote to test the validation logic. The XML and XSD files are stored on disk and are being read from there. In the actual app, the XML file would be in memory already as an XmlDocument object and the XSD would be read from an internal webserver.)

ValidationCode:(此代码来自我为测试验证逻辑而编写的一个简单应用程序。XML 和 XSD 文件存储在磁盘上并从那里读取。在实际应用程序中,XML 文件已经作为 XmlDocument 存在于内存中对象,XSD 将从内部网络服务器读取。)

private void Validate()
{
  XmlReaderSettings settings = new XmlReaderSettings();
  settings.ValidationType = ValidationType.Schema;
  //settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
  //settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
  //settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
  settings.ValidationEventHandler += new ValidationEventHandler(OnValidate);

  XmlSchemaSet schemas = new XmlSchemaSet();
  settings.Schemas = schemas;
  try
  {
    schemas.Add(null, schemaPathTextBox.Text);
    using (XmlReader reader = XmlReader.Create(xmlDocumentPathTextBox.Text, settings))
    {
      validateText.AppendLine("Validating...");
      while (reader.Read()) ;
      validateText.AppendLine("Finished Validating");
      textBox1.Text = validateText.ToString();
    }
  }
  catch (Exception ex)
  {
    textBox1.Text = ex.ToString();
  }

}

StringBuilder validateText = new StringBuilder();
private void OnValidate(object sender, ValidationEventArgs e)
{
  switch (e.Severity)
  {
    case XmlSeverityType.Error:
      validateText.AppendLine(string.Format("Error: {0}", e.Message));
      break;
    case XmlSeverityType.Warning:
      validateText.AppendLine(string.Format("Warning {0}", e.Message));
      break;
  }
}

When running the above code with the XML and XSD files defined above I get this output:

当使用上面定义的 XML 和 XSD 文件运行上面的代码时,我得到以下输出:

Validating... Error: The element 'MRIDSupportingData' in namespace 'urn:GenericLabData' has invalid child element 'MRIDNumber' in namespace 'urn:GenericLabData'. List of possible elements expected: 'MRIDNumber'. Finished Validating

正在验证...错误:命名空间“urn:GenericLabData”中的元素“MRIDSupportingData”在命名空间“urn:GenericLabData”中的子元素“MRIDNumber”无效。预期的可能元素列表:'MRIDNumber'。完成验证

What am I missing? As far as I can tell, MRIDNumber is MRIDNumber so why the error?

我错过了什么?据我所知, MRIDNumber 是 MRIDNumber 那么为什么会出现错误?

The actual XML file is much larger as well as the XSD, but it fails at the very beginning, so I have reduced the problem to almost nothing.

实际的 XML 文件和 XSD 一样大得多,但它在一开始就失败了,所以我将问题减少到几乎没有问题。

Any assistance on this would be great.

对此的任何帮助都会很棒。

Thank you,
Keith

谢谢你,
基思



BTW, These files do work:

顺便说一句,这些文件确实有效:

XML:

XML:

<?xml version='1.0'?>
<bookstore xmlns="urn:bookstore-schema">
  <book genre="novel">
    <title>The Confidence Man</title>
    <author>
      <first-name>Herman</first-name>
      <last-name>Melville</last-name>
    </author>
    <price>11.99</price>
  </book>
</bookstore>

Schema:

架构:

  <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns="urn:bookstore-schema"
    elementFormDefault="qualified"
    targetNamespace="urn:bookstore-schema">
  <xsd:element name="bookstore">
    <xsd:complexType>
      <xsd:sequence >
        <xsd:element name="book"  maxOccurs="unbounded">
          <xsd:complexType>
            <xsd:sequence >
              <xsd:element name="title" type="xsd:string"/>
              <xsd:element name="author">
                <xsd:complexType>
                  <xsd:sequence >
                    <xsd:element name="first-name"  type="xsd:string"/>
                    <xsd:element name="last-name" type="xsd:string"/>
                  </xsd:sequence> 
                </xsd:complexType>
              </xsd:element>
              <xsd:element name="price"  type="xsd:decimal"/>
            </xsd:sequence> 
            <xsd:attribute name="genre" type="xsd:string"/>
          </xsd:complexType>
        </xsd:element>
      </xsd:sequence>    
    </xsd:complexType>   
  </xsd:element>
</xsd:schema>

采纳答案by instanceof me

Try adding elementFormDefault="qualified"attribute in the xs:schemaelement of your XSD file.

尝试elementFormDefault="qualified"xs:schemaXSD 文件的元素中添加属性。

I think the validator is saying that it wants a MRIDNumberelement with no namespace, instead of your MRIDNumberelement with namespace urn:GenericLabData.

我认为验证器是说它想要一个MRIDNumber没有命名空间的元素,而不是你的MRIDNumber带有 namespace的元素urn:GenericLabData

回答by Tarnschaf

In the small excerpt of XML/XSD you are currently testing, did you include PrescribedTestDate in the XSD as well?

在您当前正在测试的 XML/XSD 的一小段摘录中,您是否也在 XSD 中包含了 PrescribedTestDate?