gpt4 book ai didi

c# - 在 Linq to XML 中检查节点是否存在

转载 作者:太空宇宙 更新时间:2023-11-03 18:15:34 26 4
gpt4 key购买 nike

我在文件夹中循环浏览了一系列 XML 文件。它们几乎总是相同的,但有时我会遇到一个文件,该文件不包含其他文件包含的元素。例如,在一个文件中,它将如下所示:

<sb_sbgp>
<itemtitle>French-Canadian</itemtitle>
<itemtype>subscription</itemtype>
<audience>French people</audience>
</sb_sbgp>

但下一个文件可能是这样的:

<sb_sbgp>
<itemtitle>Spanish</itemtitle>
<itemtype>subscription</itemtype>
</sb_sbgp>

我的问题是我不能只提取那些包含受众元素的文件(这将允许我添加一个 where 子句)。理想情况下,如果它不存在,我希望它默认为 null。这是我用来尝试完成此操作的查询:

XDocument doc = XDocument.Load(mydoc.xml);
var x = (from node in doc.Descendants("sb_sbgp")
select new
{
title = node.Element("itemtitle").Value,
type = node.Element("itemtype").Value,
audience = string.IsNullOrEmpty(node.Element("sb_sbgp_audience").Value) ? node.Element("sb_sbgp_audience").Value : null
});

我意识到这是在测试是否有值,而不是元素,但我找不到任何可以让我测试元素是否存在的东西。帮忙?

最佳答案

尝试...

XDocument doc = XDocument.Load("");
var x = (from node in doc.Descendants("sb_sbgp")
select new
{
title = node.Element("itemtitle").Value,
type = node.Element("itemtype").Value,
audience = (node.Element("sb_sbgp_audience") != null) ? node.Element("sb_sbgp_audience").Value : null
});

关于c# - 在 Linq to XML 中检查节点是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6948312/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com