如何使用 Linq to XML 根据条件提取某些子元素
我有 XML(不完全是这么简单,但足以解决我的问题)。
如果我像下面这样编码,
var xdoc = XDocument.Parse(@"
<Root>
<Item>
<Node1>Value 1</Node1>
<Node2>Value 2</Node2>
<Node3>Value 3</Node3>
<Node4>Value 4</Node4>
<Node5>Value 5</Node5>
<Node6>Value 6</Node6>
</Item>
</Root>");
var results = xdoc.Root
.Elements("Item")
.Descendants()
.Select(e => new { ElementName = e.Name, ElementValue = e.Value });
这将为我提供“Item”元素的所有后代(节点名称和节点值)的结果列表。我想问的是如何根据条件获取不同的数据集。例如,如果 Node1 或 Node2 有值(非空),那么我只想要 Node1 和 Node2 的结果列表(节点名称和值),否则结果列表应显示其他节点,即 Node3、Node4、Node5 和Node6(节点名称和值)。请帮忙。谢谢。
I have the XML (not exactly this simple but just enough for my question).
If I code like the following
var xdoc = XDocument.Parse(@"
<Root>
<Item>
<Node1>Value 1</Node1>
<Node2>Value 2</Node2>
<Node3>Value 3</Node3>
<Node4>Value 4</Node4>
<Node5>Value 5</Node5>
<Node6>Value 6</Node6>
</Item>
</Root>");
var results = xdoc.Root
.Elements("Item")
.Descendants()
.Select(e => new { ElementName = e.Name, ElementValue = e.Value });
This will give me the result list of all descendants (node name and node value) of the "Item" element. What I want to ask is how do I get different set of data depending on the condition. For example, if Node1 or Node2 has a value (not empty), then I want the result list of Node1 and Node2 (node name and value) only, otherwise the result list should show the other nodes which is Node3, Node4, Node5 and Node6 (node name and value). Please help. Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定我完全理解你的问题。但是,如果我做对了,那么您需要添加的就是这样的条件:
因此,如果
condition
为 true,那么结果序列中将只有前 2 个节点。如果condition
为 false,那么您将只有剩余的元素。我对您的问题的第一个解释是,您需要在查询中添加对
Where
的调用,以便您只能拥有结果集中实际包含值的元素。那看起来像这样:I'm not sure I completely understand your question. However, if I've got it right, then all you need to add is the condition like this:
So, if
condition
is true, then you'll only have the first 2 nodes in your result sequence. And ifcondition
is false, then you'll have only the remaining elements.My first interpretation of your question was that you needed to add a call to
Where
in your query so that you would only have the elements that actually contain a value in your result set. That would look like this:你的条件相当……奇怪。
Your conditions are rather... odd.