如何获取带空格的XElement值?

发布于 2024-12-05 20:21:31 字数 215 浏览 1 评论 0原文

我有以下 XElement:

<title>
  <bold>Foo</bold>
  <italic>Bar</italic>
</title>

当我获取 Value 属性时,它返回不带空格的 FooBar 。如何修复它?

I have following XElement:

<title>
  <bold>Foo</bold>
  <italic>Bar</italic>
</title>

When I get Value property it returns FooBar without space. How to fix it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

春夜浅 2024-12-12 20:21:32

根据定义,</code> 元素的 <code>Value</code> 是该元素中所有文本的串联。默认情况下,元素及其内容之间的空白被忽略,因此它给出“FooBar”。您可以指定要保留空格:

var element = XElement.Parse(xml, LoadOptions.PreserveWhitespace);

但是它将保留所有空格,包括换行符和缩进。在 XML 中,“Foo”和“Bar”之间有一个换行符和两个空格;它怎么会猜测你只想保留一个空格呢?

By definition, the Value of the <title> element is the concatenation of all text in this element. By default whitespace between elements and their contents is ignored, so it gives "FooBar". You can specify that you want to preserve whitespace:

var element = XElement.Parse(xml, LoadOptions.PreserveWhitespace);

However it will preserve all whitespace, including the line feeds and indentation. In your XML, there is a line feed and two spaces between "Foo" and "Bar"; how is it supposed to guess that you only want to keep one space?

时间海 2024-12-12 20:21:32

来自值的文档XElement 的 code> 属性:

获取或设置此元素的串联文本内容。

根据您的示例,这种行为是预期的。如果您想要空间,则必须提供执行此操作的逻辑。

From the documentation for the Value property of the XElement class:

Gets or sets the concatenated text contents of this element.

Given your example, this behavior is expected. If you want spaces, you will have to provide the logic to do it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文