LINQ查询,以在不存在属性时获取XML元素

本文关键字:获取 XML 元素 属性 不存在 查询 LINQ | 更新日期: 2023-09-27 18:00:08

我有这个XML:

<Config>
  <EmpFieldsMap>
    <Employee>
      <Field>
        <Name update = "false">EmpNumber</Name>
      </Field>
      <Field>
        <Name insert = "true">EmpName</Name>
      </Field>
      <Field>
        <Name insert = "true">EmpDesignation</Name>
      </Field>
    </Employee>
  </EmpFieldsMap>
</Config>

我的应用程序将执行INSERT或UPDATE,其字段将来自该xml。每个标记都将具有insert或update属性,如上面的代码片段所示。

对于插入所有具有属性的标签

insert = "true"

而不具有此属性的标签,在本例中为"EmpNumber",则必须加以考虑。

更新也是如此。

这段代码为我提供了insert属性设置为true的所有标签:

insertTags = from p in xml.Element("Config").Element("EmpFieldsMap").Elements("Field")
             where p.Element("Name").Attribute("insert") != null 
             && p.Element("Name").Attribute("insert").Value == "true"
             select p.Element("Name").Value;

删除对空的检查

insertTags = from p in xml.Element("Config").Element("EmpFieldsMap").Elements("Field")
             where p.Element("Name").Attribute("insert").Value == "true"
             select p.Element("Name").Value;

给出

对象引用未设置为实例

错误。

我在编写一个查询时遇到了问题,该查询还将包括不存在属性的标记。

有人能帮我做这个吗?

谨致问候。

LINQ查询,以在不存在属性时获取XML元素

insertTags = from p in xml.Element("Config").Element("EmpFieldsMap").Elements("Field")
    where (p.Element("Name").Attribute("insert") ?? "true") == "true"
    select p.Element("Name").Value;

有了XPath和Linq,它就更简单了:

XPathSelectElements(@"Config/EmpFieldsMap/Employee/Field/Name[@insert='true']")

此外,对于这个特定的xml,您可以使用全局搜索名称元素:

var insertTags = xdoc.XPathSelectElements(@"//Name[@insert='true']")
                     .Select(n => (string)n);

或者使用Linq查询语法:

var insertTags = from n in xdoc.Descendants("Name")
                 where (string)n.Attribute("insert") == "true"
                 select (string)n;

当您将节点值强制转换为字符串时,若节点丢失,它将不会引发异常。只返回null。所以,你不需要所有这些东西(顺便说一句,即使也不可编译):

(p.Element("Name").Attribute("insert") ?? "true") == "true"

再编辑一次。如果您正在处理布尔值,则使用布尔值而不是字符串:

var insertTags = from n in xdoc.Descendants("Name")
                 where (bool?)n.Attribute("insert") == true
                 select (string)n;

它是如何工作的?对于缺失的属性,可为null的布尔值将具有null值。将不具有值的bool?与任何布尔值进行比较产生false。因此,您将只得到那些元素,它们具有必需的属性,并且具有该属性的true

相关文章: