C# 自定义 XML 文档的验证模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16611/
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-01 08:55:32  来源:igfitidea点击:

Validation Patterns for Custom XML Documents

提问by Scott Muc

I have a web application that generates a medium sized XML dataset to be consumed by a third party.
I thought it would be a good idea to provide some form of schema document for the XML that I generate so I pasted the XML into Visual Studio and got it to generate an XSD.
The annoying thing is that my XML doesn't validate to the XSD that was generated!

我有一个 Web 应用程序,它生成一个中等大小的 XML 数据集供第三方使用。
我认为为我生成的 XML 提供某种形式的架构文档是个好主意,所以我将 XML 粘贴到 Visual Studio 中并让它生成一个 XSD。
令人讨厌的是我的 XML 没有验证生成的 XSD!

Is it better to roll your own XSD?
What about different schema docs like DTDs, Relax NG, or Schematron?

滚动自己的 XSD 会更好吗?
诸如 DTD、Relax NG 或 Schematron 之类的不同模式文档怎么样?

The key is that I would like to be able to validate my document using C#.

关键是我希望能够使用 C# 验证我的文档。

What are your XML validation strategies?

您的 XML 验证策略是什么?

回答by Vaibhav

You will be able to validate your XML with either an XML Schema or a DTD using C#. DTDs are older standards as compared to XML Schemas.

您将能够使用 C# 使用 XML 架构或 DTD 验证您的 XML。与 XML 模式相比,DTD 是较旧的标准。

So, I recommend an XML Schema approach.

因此,我推荐使用 XML Schema 方法。

回答by Nicholas Trandem

Whether you choose XSD and/or Schematron depends on what you are trying to validate. XSD is probably the most common validation strategy, but there are limits on what it can validate. If all you want to do is ensure that the right type of data is in each field, XSD should work for you. If you need to assert, for example, that the value of the <small> element is less than the value of the <big> element, or even more complex business rules involving multiple fields, you probably want Schematron or a hybrid approach.

您是否选择 XSD 和/或 Schematron 取决于您要验证的内容。XSD 可能是最常见的验证策略,但它可以验证的内容是有限的。如果您只想确保每个字段中的数据类型正确,XSD 应该适合您。例如,如果您需要断言 <small> 元素的值小于 <big> 元素的值,或者甚至涉及多个字段的更复杂的业务规则,您可能需要 Schematron 或混合方法。