Linq到Xml-如何选择具有特定XAttribute和特定XNameSpace的XElement

本文关键字:XAttribute XElement XNameSpace Xml- 何选择 选择 Linq | 更新日期: 2023-09-27 18:20:50

我有以下用于测试Web服务的简单代码:

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主控,但这种带有属性的命名空间业务确实令人困惑。

Linq到Xml-如何选择具有特定XAttribute和特定XNameSpace的XElement

这是因为Descendants()返回了2个dc:title元素。一个具有xsi:type属性,另一个没有。当您在where中没有的上调用.Value时,它会给您一个空引用异常。在检查值之前,您需要检查属性是否为null。

以下是一些有效的代码:

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