这是这个问题的一个分支Stuck on basic Linq to XML query
我正在努力提高编写 LINQ 和学习 LINQ to XML 的能力。LINQ 查询返回预期的结果,但代码看起来并不干净。有没有更好的写法?
XML
    <ApiResponse xmlns="http://api.namecheap.com/xml.response" Status="OK">
        <Errors/>
        <Warnings/>
        <RequestedCommand>namecheap.domains.check</RequestedCommand>
        <CommandResponse>
            <DomainCheckResult Domain="gooaagle.com" Available="true"/>
        </CommandResponse>
        <Server>WEB1-SANDBOX1</Server>
        <GMTTimeDifference>--4:00</GMTTimeDifference>
        <ExecutionTime>0.859</ExecutionTime>
    </ApiResponse>
C#
XNamespace ns = "http://api.namecheap.com/xml.response";
var response = (
    from r in doc.Elements()
    select new
    {
        Errors = r.Element(ns + "Errors").Value,
        Warnings = r.Element(ns + "Warnings").Value,
        RequestedCommand = r.Element(ns + "RequestedCommand").Value,
        CommandResponse = new
                      {
                         Domain= r.Element(ns + "CommandResponse").Element(ns + "DomainCheckResult").Attribute("Domain"),
                         Available = r.Element(ns + "CommandResponse").Element(ns + "DomainCheckResult").Attribute("Available")
                      },
       Server = r.Element(ns + "Server").Value
    });