Reputation: 95
XDocument.Parse
is retaining unwanted white space when parsing my XML. It appears that my XML is "not indented," which means that white space is retained regardless of whether or not I send in the LoadOptions.PreserveWhitespace
flag (http://msdn.microsoft.com/en-us/library/bb551294(v=vs.110).aspx).
This means that when I have XML like the following:
<?xml version="1.0" encoding="UTF-8"?>
<blah:Root xmlns:blah="example.blah.com">
<blah:Element>
value
</blah:Element>
</blah:Root>
and then look at
XDocument xDoc = XDocument.Parse(blahXml);
xElement xEl = xDoc.Root.Element("Element");
string value = xEl.Value;
print value;
it will print "\n value\n"
instead of "value"
.
How do I make XDocument.Parse
always ignore white space regardless of whether or not I give it indented or not-indented XML?
Upvotes: 2
Views: 1569
Reputation: 167516
White space between elements can be ignored (e.g.
<root>
<foo>foo 1</foo>
<foo>foo 2</foo>
</root>
can be parsed into a root
element nodes with two foo
child elements node if white space is ignored or into a root
element node with five child nodes: text node, foo
element node, text node, foo
element node, text node), but if an element contains some text data that includes white space then it is considered important. So your only option is indeed to use a method like Trim
in the .NET framework or like normalize-space
in XPath to have the white space removed when you process the element.
Upvotes: 1