【问题标题】:In C#, how to determine the XSD-defined MaxLength for an element在 C# 中,如何确定元素的 XSD 定义的 MaxLength
【发布时间】:2009-10-20 16:23:52
【问题描述】:

我正在使用带有附加 XSD 的 XmlReader 进行验证。

在读取和验证我的 XML 文档时,我想在我的 C# 代码中确定 XSD 中为特定元素指定的“maxLength”值。例如,我的 XSD 片段非常简单地定义为:

<xsd:element name="testing" minOccurs="0">
    <xsd:simpleType>
        <xsd:restriction base="xsd:string">
            <xsd:maxLength value="10"/>
        </xsd:restriction>
    </xsd:simpleType>
</xsd:element>

我可以使用以下方法轻松获得“minOccurs”值:

myReader.SchemaInfo.SchemaElement.MinOccurs;

但是我如何获得“maxLength”值(在我上面的示例片段中的值为 10)???

我认为“myReader.SchemaInfo.SchemaElement.Constraints”可能会给我这些信息,但该集合的“计数”始终为零。

谢谢,

拍拍。

【问题讨论】:

    标签: c# xsd maxlength


    【解决方案1】:

    你会在这里找到:Accessing XML Schema Information During Document Validation 一个很好的解释如何做到这一点及更多。

    【讨论】:

    • +1 不确定它是否解决了 OP 的问题,但非常有用的信息。
    • Yahoo - 得到它的工作,这个答案正是我需要的信息!尽管由于无法获取此信息,我的代码有点复杂。 'Text' 节点,因此必须跳到 'EndElement' 节点 - 但到底是什么,它现在正在工作。谢谢一百万!
    • 2 年后,这个答案仍然是我设法在 SchemaInfo 对象模型上找到的最佳信息。对于任何希望了解 SchemaInfo 对象的人来说,这是一个很好的链接。需要一些工作来修改它以满足您的需求,但这是我迄今为止找到的唯一方法
    【解决方案2】:

    使用 myReader.SchemaInfo 可以做到这一点(请参阅 najmeddine 的回复),但如果您需要访问未在 SchemaInfo 对象中公开的内容...

    ..XSD 是一种 XML 语言。您可以简单地加载 XSD 文件并使用 XPath 找到“测试”元素的定义及其 maxLength。

    【讨论】:

    • 如果您可以直接进入 SchemaInfo,那就太好了,因为该信息似乎已经存在于阅读器中。
    • 同意,罗伯特。似乎 najmeddine 解决方案指向了这个方向,但是 SchemaInfo 的对象模型并没有得到很好的记录(至少我没有找到正确的文档),因此在普通 XML DOM 有点乏味但陈旧的方式。
    【解决方案3】:

    我今天遇到了问题,链接不再工作。

    这是你需要的扩展方法

    public static int GetXsdFieldMaxLength(this XmlReader reader)
    {
        var schemaType = reader.SchemaInfo.SchemaType;
        if (schemaType is XmlSchemaSimpleType simpleType)
        {
            XmlSchemaSimpleTypeContent content = simpleType.Content;
    
            // see XmlSchemaSimpleTypeRestriction source code for list of all facet types
            if (content is XmlSchemaSimpleTypeRestriction restriction)
            {
                // XmlSchemaFacet facet
                foreach (XmlSchemaObject facet in restriction.Facets)
                {
                    if (facet is XmlSchemaMaxLengthFacet ml)
                    {
                        // the Value is a string, convert it to an int
                        return ml.Value.ToInt();
                    }
                }
            }
        }
    
        return -1;
    }
    

    然后您可以在 XML 验证代码中使用该函数,如下所示:

    // var settings = new XmlReaderSettings();
    settings.ValidationEventHandler += (object sender, ValidationEventArgs args) =>
    {
        // the actual int MaxLength is missing in the Validation Error
        var reader = sender as XmlReader;
        var maxLength = reader.GetXsdFieldMaxLength();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-19
      • 2016-03-07
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多