2013-02-20 87 views
-1

我有这样的XML:LINQ查询来获取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或更新其字段将来自这个XML。 每个标签将具有插入或更新属性,如上面的代码片段所示。

对于插入所有具有属性

insert = "true" 

标签和不具有这个属性的标签,在这种情况下,“EmpNumber”,必须加以考虑。

同样适用于更新。

此代码给了我所有插件属性设置为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; 

给未设置

对象参考实例

错误。

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

有人可以帮助我吗?

问候。

回答

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

什么是 - ?? - 在做什么? – Gero 2013-02-20 12:19:06

+0

@Gero - 这是[null coalescing operator](http://msdn.microsoft.com/zh-cn/library/ms173224.aspx)。如果'insert'属性返回null,则将其替换为'true'。 – 2013-02-21 00:47:36

0

在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缺失属性的值。将没有值的bool?与任何布尔值比较产生false。因此,您将只获得那些具有所需属性的元素,并且该元素具有该属性的true