【问题标题】:Get whitespace in XElement获取 XElement 中的空格
【发布时间】:2011-04-27 23:08:42
【问题描述】:
我知道这有点愚蠢,但我正在转换的 XML 有时有一个元素,它只是一个或两个空格。像这样:
Dim es1 = <Text> </Text>
当我尝试像Dim resultText = es1.Value 一样获取.Value 时,它只是一个空字符串。如果元素中有前导和/或尾随空格以及至少一个其他字符,这不是问题。
如果这就是全部,是否有强制.Value给我空白?
【问题讨论】:
标签:
.net
vb.net
linq-to-xml
whitespace
xelement
【解决方案1】:
解析 XML 时使用 LoadOptions.PreserveWhitespace。 C#示例代码:
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 文字,但我假设通常你实际上是从文件等中解析:)
【解决方案2】:
加载您的 XDocument:
LoadOptions.PreserveWhitespace
【解决方案3】:
如果您需要带有空格的 XML 文字,请使用嵌入式表达式。这个例子有两个空格。
Dim TwoSpaces As XElement = <f><%= " " %></f>
Dim s As String = TwoSpaces.Value