【问题标题】:Read data from XElement that has elements mixed with plain content从 XElement 中读取元素与纯内容混合的数据
【发布时间】:2012-06-05 13:10:21
【问题描述】:

XElement 具有以下值:

<parent><child>text inside element</child>and plain content</parent>

如何将其转换为包含:“元素内的文本和纯内容”的字符串。

我已经尝试过什么?

我厌倦了使用xElement.Value,但这将两个节点连接起来而不在它们之间放置空格:“元素内的文本和纯内容”。

【问题讨论】:

  • 无复制。我看到.Value 有很多空格和换行符。
  • 我猜xml应该是&lt;parent&gt;&lt;child&gt;text inside element&lt;/child&gt;and plain content&lt;/parent&gt;

标签: c# .net xml linq-to-xml xelement


【解决方案1】:

您要查找的文本存储在 XText 类型的节点中。所以你可以像这样访问这些节点:

xElement.DescendantNodes()
        .OfType<XText>()
        .Select(t => t.Value)

这会给你这个结果:

text inside element 
and plain content 

然后,您可以根据需要连接它们(例如使用String.Join)。

【讨论】:

  • @HenkHolterman 是的,如果他想确保值之间只有一个空格,这将是一个好主意。
猜你喜欢
  • 2012-10-05
  • 2013-04-17
  • 1970-01-01
  • 1970-01-01
  • 2014-10-13
  • 2013-06-20
  • 2013-05-10
  • 1970-01-01
  • 2013-02-23
相关资源
最近更新 更多