2013-07-06 52 views
0

我有XML,看起來像選擇從具有匹配某些情況c#LINQ

<?xml version="1.0"?> 
    <configuration> 
     <TemplateMapper> 
     <Template XML="Product.xml" XSLT="sheet.xslt" Keyword="Product" /> 
     <Template XML="Cart.xml" XSLT="Cartsheet.xslt" Keyword="Cart" /> 
     </TemplateMapper> 
    </configuration> 

當我通過在屬性關鍵字的值爲「產品」我想LINQ到一個屬性的XML元素的屬性的多個值將XML和XSLT屬性的值返回爲字符串和字符串的字典。

到目前爲止我試過:

   var Template="Product" 
       var dictionary = (from el in xmlElement.Descendants("TemplateMapper") 
           let xElement = el.Element("Template") 
           where xElement != null && xElement.Attribute("Keyword").Value == Template 
           select new 
             { 
              XML = el.Attribute("XML").Value, 
              XSLT= el.Attribute("XSLT").Value 
             }).ToDictionary(pair => pair.XML, pair => pair.XSLT); 

      KeyValuePair<string, string> templateValues = dictionary.FirstOrDefault(); 

它給是一個錯誤「不設置到對象的實例對象引用」。任何人都可以發現我在做什麼錯誤?非常感謝。

回答

0

我會嘗試以下操作:

var dictionary = (from t in xdoc.Root.Element("TemplateMapper").Elements("Template") 
        where (string)t.Attribute("Keyword") == Template 
        select new { 
         XML = (string)t.Attribute("XML"), 
         XSLT = (string)t.Attribute("XSLT") 
        }).ToDictionary(x => x.XML, x => x.XSLT); 

(string)XAttribute不拋出一個異常時,未找到屬性,所以最好是XAttribute.Value

+0

真棒非常感謝主席先生! – Bravo11

0

與此

  var Template="Product" 
      var dictionary = (from el in xmlElement.Descendants("TemplateMapper") 
          let xElement = el.Element("Template") 
          where xElement != null && xElement.Attribute("Keyword").Value == Template 
          select new 
            { 
             XML = xElement .Attribute("XML").Value, 
             XSLT= xElement .Attribute("XSLT").Value 
            }).ToDictionary(pair => pair.XML, pair => pair.XSLT); 

     KeyValuePair<string, string> templateValues = dictionary.FirstOrDefault(); 

更換您的代碼是在元素目前的XElement不EL

相關問題