Search code examples
c#xmlxmldocument

How to ignore leading whitespace in XML file?


I need to load xml from a file into an XmlDocument. The problem is that the file contains some leading whitespace. (I have no control over the system that produces the file.) Is there any clean/easy way to ignore or strip those characters?

string SamplelRequestFile = @"C:\example.xml";
XmlDocument docXML = new XmlDocument(); 
XmlTextReader xReader = new XmlTextReader(SamplelRequestFile);
XmlReaderSettings ReaderSettings = new XmlReaderSettings();
ReaderSettings.XmlResolver = null;
ReaderSettings.ProhibitDtd = false;
docXML.Load(xReader);

example.xml (note the leading spaces)

  <?xml version="1.0" ?>
<myRoot>
<someElement />
</myRoot>

Solution

  • You'll just have to do something like

     using (StreamReader sr = new StreamReader(@"C:\example.xml"))
     {
          XmlDocument docXML = new XmlDocument(); 
          docXML.LoadXml(sr.ReadToEnd().Trim());
          ...
     }