如何在 C#2.0 中验证 XML 文件
我需要有关如何简单地验证 Xml 文件的帮助?
我用谷歌搜索,发现一些教程说开发人员可以根据现有的 XSD 架构文件验证 XML 文件。(如下 snppet)。
就我而言,我没有 Xsd 文件。我能做些什么?我必须使用 XSD.exe 等工具生成 Xsd 文件吗?
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add("", "c:\mySchema.xsd");
settings.ValidationEventHandler += new ValidationEventHandler(OnValidationError);
XmlReader reader = XmlReader.Create("", settings);
XPathDocument doc = new XPathDocument(reader);
XPathNavigator navigatore = doc.CreateNavigator();
实际上我需要的验证是一个非常简单的用法。只需确保所有 xml 列出的项目/内部子项目都配对即可。我将打开并写入我的XML,但有时由于某种原因我的XML无法成功写入。然后当我下次加载 XML 时,我的应用程序将抛出异常。这就是为什么我需要在加载 xml 文件之前验证它。
感谢您的意见和建议。
I need help on how to validate Xml file simply?
I googled and found some tutorial said about developer can validate XML file based on an exist XSD schema file.(as below snppet).
For my case, I don't have an Xsd file. What can I do? Must I generate an Xsd file with a tool like XSD.exe?
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add("", "c:\mySchema.xsd");
settings.ValidationEventHandler += new ValidationEventHandler(OnValidationError);
XmlReader reader = XmlReader.Create("", settings);
XPathDocument doc = new XPathDocument(reader);
XPathNavigator navigatore = doc.CreateNavigator();
Actually the validation what I need is a very simple usage. Just make sure all the xml listed items/inner sub-items are paired. I will open and write my XML, but my XML can't be written successfully for some reason some time. Then when I load my XML next time, my Application will throw exception. That's why I need validate my xml file before load it.
Appreciated for your comments and suggestions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您没有 xsd,您应该创建一个。如果您想验证任何特定结构,这是您的最佳选择。
如果您只是想确保文档由有效的 XML 组成,您可以不使用 XML,但如果您关心架构,那么您必须创建一个架构定义。
您可以编写自己的 XSD 或使用任意数量的工具。我的建议是自己写。这并不难,而且值得知道如何去做。
以下是帮助您入门的链接:http://www.w3schools.com/schema/default。 ASP
If you don't have an xsd you should create one. If you are trying to validate any specific structure this is your best option.
If you just want to make sure a document is made up of valid XML you could get away with not having one but if you care about the schema then you must create a schema definition.
You can write your own XSD or use any number of tools. My advice is to write your own. It's not hard and it's worth knowing how to do.
Here is a link to get you started: http://www.w3schools.com/schema/default.asp