繁体   English   中英

Linq to Xml - 如何使用具有特定XNameSpace的特定XAttribute选择XElement

[英]Linq to Xml - how to select XElement with a specific XAttribute with a specific XNameSpace

我有以下用于测试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 master,但这个带有属性的命名空间业务真的很混乱。

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

这里有一些有用的代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM