本文介绍了在将XML文件读入XmlDocument时如何忽略注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我想用C#读取一个XML文档,我这样做:I am trying to read a XML document with C#, I am doing it this way:XmlDocument myData = new XmlDocument();myData.Load("datafile.xml");无论如何,我有时候在阅读XmlNode.ChildNodes时获得注释。anyway, I sometimes get comments when reading XmlNode.ChildNodes.对于遇到同样要求的人来说,这里是我最后做的:For the benefit of who's experiencing the same requirement, here's how I did it at the end:/** Validate a file, return a XmlDocument, exclude comments */private XmlDocument LoadAndValidate( String fileName ){ // Create XML reader settings XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreComments = true; // Exclude comments settings.ProhibitDtd = false; settings.ValidationType = ValidationType.DTD; // Validation // Create reader based on settings XmlReader reader = XmlReader.Create(fileName, settings); try { // Will throw exception if document is invalid XmlDocument document = new XmlDocument(); document.Load(reader); return document; } catch (XmlSchemaException) { return null; }}谢谢 Tommaso Thank youTommaso推荐答案您可以使用 XmlReader 与 XmlReaderSettings.IgnoreComments 设置为true:You can use an XmlReader with XmlReaderSettings.IgnoreComments set to true:XmlReaderSettings readerSettings = new XmlReaderSettings();readerSettings.IgnoreComments = true;using (XmlReader reader = XmlReader.Create("input.xml", readerSettings)){ XmlDocument myData = new XmlDocument(); myData.Load(reader); // etc...} =http://social.msdn.microsoft.com/forums/en-US/xmlandnetfx/thread/99ae3ee6-efd1-4867-ad7e-f4ab8950db6e =nofollow noreferrer>此处通过搜索 XmlDocument忽略注释 )(Found from here by searching for XmlDocument ignore comments) 这篇关于在将XML文件读入XmlDocument时如何忽略注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-10 20:10