为什么我的 XML 验证针对其架构失败? [英] Why is my XML validation failing against its schema?

查看:25
本文介绍了为什么我的 XML 验证针对其架构失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我已将问题简化为最基本的元素,但遇到了问题.

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

XML:

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

架构:

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

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.)

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;
  }
}

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

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

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

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

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

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

实际的 XML 文件和 XSD 一样大得多,但它一开始就失败了,所以我把问题缩小到几乎没有问题.

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.

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

Any assistance on this would be great.

谢谢,
基思

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

BTW, These files do work:

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>

架构:

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

推荐答案

尝试在 XSD 文件的 xs:schema 元素中添加 elementFormDefault="qualified" 属性.

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

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

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

这篇关于为什么我的 XML 验证针对其架构失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆