2

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.

2
  • Did you check this: stackoverflow.com/questions/393840/…
    – Saravanan
    May 24, 2013 at 10:19
  • @saravanan I just had a look. I am not in the same situation. If instead of using an xpath query, I move my navigator to element <root> and then MoveToFirstChild() just fails. The XPathDocument seems to be ignoring my whitespace node altogether.
    – TiMoch
    May 24, 2013 at 10:24

1 Answer 1

4

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/

2
  • btw, feel free to accept your own answer if it solves your problem.
    – alex.b
    May 24, 2013 at 12:06
  • @aleksey.berezan stackoverflow asks me to wait for a couple of days before I can do that
    – TiMoch
    May 24, 2013 at 12:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.