Get spaces in XElement

I know this is a little stupid, but the XML I convert sometimes has an element that is just a single or double space. Like this:

Dim es1 = <Text> </Text>

When I try to get .Valuethis type Dim resultText = es1.Value, it is just an empty string. This is not a problem if the element has leading and / or trailing spaces and at least one other character in the element.

Is there a way to force .Valueme to give a space if that's all there is?

+5
source share
3 answers

Use LoadOptions.PreserveWhitespacewhen parsing XML. C # example 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

    }
}

(, Load, Parse ..)

, VB XML, , ..:)

+6

XDocument

LoadOptions.PreserveWhitespace
+2

If you need an XML literal with a space, use the inline expression. This example has two spaces.

    Dim TwoSpaces As XElement = <f><%= "  " %></f>
    Dim s As String = TwoSpaces.Value
+1
source

All Articles