2013-02-20 95 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