19

我有这样的XML结果

<response>
  <lst name="responseHeader">
    <int name="status">0</int>
    <int name="QTime">16</int>
  </lst>
  <result name="response" numFound="3" start="0" maxScore="1.0">
    <doc>
      <str name="ContaFirstname">
        firstname1                                                   
      </str>
      <str name="ContaId">6557</str>
      <str name="ContaJobTitle">Manager</str>
      <str name="ContaSurname">surname1
      </str>
    </doc>
    <doc>
      <str name="ContaFirstname">firstname2</str>
      <str name="ContaId">6203</str>
      <str name="ContaJobTitle">Director</str>
      <str name="ContaSurname">surname2</str>
    </doc>
  </result>
</response>

我想得到一个对象列表,每个对象都包含ContaFirstname,ContaIdContaJobTitleContaSurname

我尝试过这样的事情,但这是不对的,因为我把它们都设为 NULL

var test = from c in xml.Descendants("doc")
                    select new 
                    {
                        firstname = c.Element("ContaFirstname"),
                        surnmane = c.Element("ContaSurname")
                    }; 

那么如何通过名称访问这些元素呢?

4

2 回答 2

32

您不想按名称访问元素,因为大多数人会解释该语句。您想通过其name属性的值访问元素:

firstname = (string) c.Elements("str")
                      .First(x => x.Attribute("name").Value == "ContaFirstname");
//etc

您可能很想将其抽象为一个单独的方法,因为多次这样做会很痛苦。例如:

public static XElement ElementByNameAttribute(this XContainer container,
                                              string name)
{
    return container.Elements("str")
                    .First(x => x.Attribute("name").Value == name);
}

然后:

var test = from c in xml.Descendants("doc")
           select new 
           { 
               firstname = c.ElementByNameAttribute("ContaFirstname").Value,
               surnmane = c.ElementByNameAttribute("ContaSurname").Value
           }; 

如果您有机会为您的文档提供更合理的结构,那将是更可取的...

于 2013-01-24T14:52:52.587 回答
3

这是否解决了您的问题:

var test = from c in xml.Descendants("doc")
           select new 
           {
               firstname = c.Elements("str").First(element => element.Attribute("name").Value == "ContaFirstname"),
               surnmane = c.Elements("str").First(element => element.Attribute("name").Value == "ContaSurname")
           }; 

或者,如果您想要这些值(而不是XElement

var test = from c in xml.Descendants("doc")
           select new 
           {
               firstname = c.Elements("str").First(element => element.Attribute("name").Value == "ContaFirstname").Value,
               surnmane = c.Elements("str").First(element => element.Attribute("name").Value == "ContaSurname").Value
           }; 
于 2013-01-24T15:00:52.847 回答