2012-01-20 26 views
3

我已經爲測試Web服務下面的簡單代碼:的LINQ到XML - 如何與一個特定的XNamespace特定XAttribute選擇的XElement

using System; 
using System.Linq; 
using System.Xml; 
using System.Xml.Linq; 
using System.Collections.Generic; 

namespace Testing_xmlReturn 
{ 
    class MainClass 
    { 
     public static void Main (string[] args) 
     { 
     // Default namespaces 
     XNamespace df = @"http://oss.dbc.dk/ns/opensearch"; 
     XNamespace dkdcplus = @"http://biblstandard.dk/abm/namespace/dkdcplus/"; 
     XNamespace ac = @"http://biblstandard.dk/ac/namespace/"; 
     XNamespace dcterms = @"http://purl.org/dc/terms/"; 
     XNamespace dkabm = @"http://biblstandard.dk/abm/namespace/dkabm/"; 
     XNamespace dc = @"http://purl.org/dc/elements/1.1/"; 
     XNamespace oss = @"http://oss.dbc.dk/ns/osstypes"; 
     XNamespace xsi = @"http://www.w3.org/2001/XMLSchema-instance"; 

     XDocument xd = new XDocument(); 
     xd = XDocument.Load(@"http://opensearch.addi.dk/next_2.0/?action=search&query=mad&stepValue=1&sort=date_descending&outputType=xml"); 


     var q = from result in xd.Descendants(dkabm + "record").Elements(dc + "title") 
      where result.Attribute(xsi + "type").Value == "dkdcplus:full" 
      select result; 

     foreach(XElement xe in q) 
       Console.WriteLine("Name: " + xe.Name +" Value: " + xe.Value); 

     Console.ReadLine(); 

     } 
    } 
} 

的的XElement我需要從響應得到的是:

<dc:title xsi:type="dkdcplus:full">Dynastiet præsenterer D-Dag!</dc:title> 

我不斷收到一個System.NullReferenceException。顯然,我沒有得到XElement,但爲什麼?

很容易通過刪除「where」來獲取所有dc:title元素,所以這就成了問題。

我不是Linq-to-Xml master,但是這個帶有屬性的命名空間業務真的讓人困惑。

回答

1

這是因爲有Descendants()返回了2 dc:title元素。一個具有xsi:type屬性,另一個沒有。當您在沒有where的電話上撥打.Value時,它會爲您提供空參考例外。在檢查該值之前,您需要檢查該屬性是否爲空。

下面是一些代碼,工程:

var q = from result in xd.Descendants(dc + "title") 
    where (String)result.Attribute(xsi + "type") == "dkdcplus:full" 
    select result; 
相關問題