Question

I have the following code

var textReader = new StringReader("<root>    </root>");
var settings = new XmlReaderSettings();
settings.IgnoreWhitespace = false;
var reader = XmlReader.Create(textReader, settings);
var doc = new XPathDocument(reader);
var nav = doc.CreateNavigator();
var ws = nav.SelectSingleNode("/root/text()");

Note the whitespace in my root node.

ws is null. Why is that?

I could find examples where unwanted whitespace nodes crept up in a query's result but I could not find the other way around.

Thanks

Edit: If my xml is

<root xml:space="preserve">    </root>

the query works fine. But in this case the node is of type SignificantWhitespace, not Whitespace.

Was it helpful?

Solution

One of those "Haha" moments...

XPathDocument has a constructor overload that takes an XmlSpace enum value. XPathDocument will ignore non-significant whitespace nodes if provided with no XmlSpace value or XmlSpace.Default To be able to select non-significant whitespace nodes, you need to pass XmlSpace.Preserve.

See : http://timoch.com/blog/2013/05/xpathdocument-and-whitespaces/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top