Search code examples
.netvb.netlinq-to-xmlwhitespacexelement

Get whitespace in XElement


I know this is a bit stupid, but XML I'm transforming sometimes has an element that is just a single or double whitespace. Like this:

Dim es1 = <Text> </Text>

When I try to get the .Value of this like Dim resultText = es1.Value, it's just an empty string. This isn't a problem if there is leading and/or trailing whitespace and at least one other character in the element.

Is there anyway to coerce .Value to give me white space if that is all there is?


Solution

  • Use LoadOptions.PreserveWhitespace when you parse the XML. C# sample code:

    using System;
    using System.Xml.Linq;
    
    class Test
    {
        static void Main()
        {
            string xml = "<Foo> </Foo>";
    
            XElement withWhitespace = XElement.Parse(xml,
                LoadOptions.PreserveWhitespace);
            Console.WriteLine(withWhitespace.Value.Length); // Prints 1
            XElement withoutWhitespace = XElement.Parse(xml);
            Console.WriteLine(withoutWhitespace.Value.Length); // Prints 0
    
        }
    }
    

    (Obviously this is available when using Load as well as Parse, etc.)

    I don't know how that fits in with VB XML literals, but I'll assume that normally you're actually parsing from a file etc :)