This question already has an answer here:
I am trying to read a XML document with C#, I am doing it this way:
XmlDocument myData = new XmlDocument();
myData.Load("datafile.xml");
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
You can use an
XmlReader
withXmlReaderSettings.IgnoreComments
set to true:(Found from here by searching for
XmlDocument ignore comments
)You could simply add filter on your ChildNodes. E.g.
Alternatively, you could load the XmlDocument passing in an XmlReader with settings such that XmlReaderSettings.IgnoreComments is true.
If you want to use an XmlDocument instead of an XmlReader, you might be better off referring to child nodes by name or using XPath.
Then you don't need to worry about comments that have been added, or other nodes, or if the order has changed.
This will select "SomeChildNode", a child of the root element.
The next example will loop through all books in books.xml and print the author. It uses the string property selector and Xpath. It shouldn't be affected by comments etc.
Note, with XPath, you could just as easily search for all book elements in the document, using something like ".//book".
books.xml:
References:
XmlNode.Item Property (String) hxxp://msdn.microsoft.com/en-us/library/sss31aas.aspx XmlNode.SelectNodes Method (String) http://msdn.microsoft.com/en-us/library/hcebdtae.aspx XmlNode.SelectSingleNode Method (String) http://msdn.microsoft.com/en-us/library/fb63z0tw.aspx
use
XmlReaderSettings