本文介绍了如何读取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;
}
}
感谢您
托马索
Thank you
Tommaso
推荐答案
您可以使用的,提供的设置为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...
}
(从的)
(Found from here by searching for XmlDocument ignore comments
)
这篇关于如何读取XML文件到一个XmlDocument的时候忽略评论?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!