开发者

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 p开发者_开发问答roblem 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?


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 :)


Load your XDocument with:

LoadOptions.PreserveWhitespace


If you need a XML literal with white space use an embedded expression. This example has two spaces.

    Dim TwoSpaces As XElement = <f><%= "  " %></f>
    Dim s As String = TwoSpaces.Value
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜