【问题标题】:Linq to Xml - how to select XElement with a specific XAttribute with a specific XNameSpaceLinq to Xml - 如何选择具有特定 XNameSpace 的特定 XAttribute 的 XElement
【发布时间】:2012-01-20 22:09:07
【问题描述】:

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

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

【问题讨论】:

    标签: c# linq-to-xml


    【解决方案1】:

    这是因为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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-28
      • 1970-01-01
      相关资源
      最近更新 更多