Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 关于构造/格式化LINQ到XML查询的最佳方法的建议?_C#_Xml_Linq_Linq To Xml - Fatal编程技术网

C# 关于构造/格式化LINQ到XML查询的最佳方法的建议?

C# 关于构造/格式化LINQ到XML查询的最佳方法的建议?,c#,xml,linq,linq-to-xml,C#,Xml,Linq,Linq To Xml,我已经编写了一个LINQ到XML的查询,它满足了我的需求,但它看起来非常难看。我想知道,你们如何以一种看起来不那么花哨的方式格式化下面的查询 如果我的示例有点冗长,请道歉 我查询的XML文档具有以下结构: <?xml version="1.0" encoding="iso-8859-1"?> <newsitem itemid="1" id="root" date="1996-08-20" xml:lang="en"> <title>A title<

我已经编写了一个LINQ到XML的查询,它满足了我的需求,但它看起来非常难看。我想知道,你们如何以一种看起来不那么花哨的方式格式化下面的查询

如果我的示例有点冗长,请道歉

我查询的XML文档具有以下结构:

<?xml version="1.0" encoding="iso-8859-1"?>
<newsitem itemid="1" id="root" date="1996-08-20" xml:lang="en">
    <title>A title</title>
    <headline>A headline</headline>
    <dateline>A dateline</dateline>
    <text>
        Some text
    </text>
    <metadata>
        <codes class="">
            <code code="">
                <editdetail attribution=""/>
            </code>
        </codes>
        <dc element="dc.date.created" value=""/>
        <dc element="dc.publisher" value=""/>
        <dc element="dc.date.published" value=""/>
        <dc element="dc.source" value=""/>
        <dc element="dc.creator.location" value=""/>
        <dc element="dc.creator.location.country.name" value=""/>
        <dc element="dc.source" value=""/>
    </metadata>
</newsitem>
谢谢

最主要的“丑陋”是底部的东西。我可能会添加一个扩展方法(或者只是一个实用方法)——类似于:

    public static XAttribute GetMetadata(this XElement parent, string key)
    {
        return parent.Elements("metadata").Elements("dc")
                 .FirstOrDefault(x => x.Attribute("element").Value == key)
                 .Attribute("value");
    }
Publisher = (string)article.GetMetadata("dc.publisher");
然后,您应该能够使用以下内容:

    public static XAttribute GetMetadata(this XElement parent, string key)
    {
        return parent.Elements("metadata").Elements("dc")
                 .FirstOrDefault(x => x.Attribute("element").Value == key)
                 .Attribute("value");
    }
Publisher = (string)article.GetMetadata("dc.publisher");
(未选中)

.DefaultIfEmpty()实现了什么功能?