Reputation: 483
I have the following simple code for testing a webservice :
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();
}
}
}
The XElement i need to get from the response is :
<dc:title xsi:type="dkdcplus:full">Dynastiet præsenterer D-Dag!</dc:title>
I keep getting a System.NullReferenceException. Clearly I don't get the XElement but why ?
It's easy to get all the dc:title elements out by removing "where" so thats got to be the problem.
I'm no Linq-to-Xml master but this namespace business with attributes is really confusing.
Upvotes: 3
Views: 3099
Reputation: 52798
It's because there are 2 dc:title
elements returned by the Descendants()
. One with a xsi:type
attribute and one without. When you call .Value
on the one without in your where
it gives you a null reference exception. You need to check for the attribute been null before you inspect the value.
Here's some code that works:
var q = from result in xd.Descendants(dc + "title")
where (String)result.Attribute(xsi + "type") == "dkdcplus:full"
select result;
Upvotes: 1