基于附加条件选择特定子元素的Linq-to-XML查询

5

以下是我的当前的LINQ查询和示例XML。我想要做的是从email-addresses元素中选择主电子邮件地址并将其放入User.Email属性中。

  • type元素为primary时,它位于email-address元素下。
  • email-addresses下可能有多个元素,但只有一个会被标记为主要。

在这里采取的最简单方法是什么?

当前的Linq查询(User.Email目前为空):

var users = from response in xdoc.Descendants("response")
            where response.Element("id") != null
            select new User
                       {
                           Id = (string)response.Element("id"),
                           Name = (string)response.Element("full-name"),
                           Email = (string)response.Element("email-addresses"),
                           JobTitle = (string)response.Element("job-title"),
                           NetworkId = (string)response.Element("network-id"),
                           Type = (string)response.Element("type")
                       };

示例XML:

<?xml version="1.0" encoding="UTF-8"?>
<response>
  <response>
    <contact>
      <phone-numbers/>
      <im>
        <provider></provider>
        <username></username>
      </im>
      <email-addresses>
        <email-address>
          <type>primary</type>
          <address>alice@domain.com</address>
        </email-address>
      </email-addresses>
    </contact>
    <job-title>Account Manager</job-title>
    <type>user</type>
    <expertise nil="true"></expertise>
    <summary nil="true"></summary>
    <kids-names nil="true"></kids-names>
    <location nil="true"></location>
    <guid nil="true"></guid>
    <timezone>Eastern Time (US &amp; Canada)</timezone>
    <network-name>Domain</network-name>
    <full-name>Alice</full-name>
    <network-id>79629</network-id>
    <stats>
      <followers>2</followers>
      <updates>4</updates>
      <following>3</following>
    </stats>
    <mugshot-url>
      https://assets3.yammer.com/images/no_photo_small.gif</mugshot-url>
      <previous-companies/>
      <birth-date></birth-date>
      <name>alice</name>
      <web-url>https://www.yammer.com/domain.com/users/alice</web-url>
      <interests nil="true"></interests>
      <state>active</state>
      <external-urls/>
      <url>https://www.yammer.com/api/v1/users/1089943</url>
      <network-domains>
        <network-domain>domain.com</network-domain>
      </network-domains>
      <id>1089943</id>
      <schools/>
      <hire-date nil="true"></hire-date>
      <significant-other nil="true"></significant-other>
    </response>
  <response>
    <contact>
      <phone-numbers/>
      <im>
        <provider></provider>
        <username></username>
      </im>
      <email-addresses>
        <email-address>
          <type>primary</type>
          <address>bill@domain.com</address>
        </email-address>
      </email-addresses>
    </contact>
    <job-title>Office Manager</job-title>
    <type>user</type>
    <expertise nil="true"></expertise>
    <summary nil="true"></summary>
    <kids-names nil="true"></kids-names>
    <location nil="true"></location>
    <guid nil="true"></guid>
    <timezone>Eastern Time (US &amp; Canada)</timezone>
    <network-name>Domain</network-name>
    <full-name>Bill</full-name>
    <network-id>79629</network-id>
    <stats>
      <followers>3</followers>
      <updates>1</updates>
      <following>1</following>
    </stats>
    <mugshot-url>
      https://assets3.yammer.com/images/no_photo_small.gif</mugshot-url>
      <previous-companies/>
      <birth-date></birth-date>
      <name>bill</name>
      <web-url>https://www.yammer.com/domain.com/users/bill</web-url>
      <interests nil="true"></interests>
      <state>active</state>
      <external-urls/>
      <url>https://www.yammer.com/api/v1/users/1089920</url>
      <network-domains>
        <network-domain>domain.com</network-domain>
      </network-domains>
      <id>1089920</id>
      <schools/>
      <hire-date nil="true"></hire-date>
      <significant-other nil="true"></significant-other>
    </response>
</response>

主元素始终设置为true吗? - John Saunders
是的,总是有一个主要元素设置为true。我并不喜欢这个XML格式,而且我对它没有控制权 ;) - Brian Lyttle
1
多谢@Metro Surf的答案,它帮我解决了一个问题(https://dev59.com/3FbTa4cB1Zd3GeqP_o2x)。 - meffordm
2个回答

6

使用Lambda表达式:

var users = xdoc.Root.Elements( "response" )
    .Where( x => !string.IsNullOrEmpty( x.Element( "id" ).Value ) )
    .Select( x => new User
              {
                Id = x.Element( "id" ).Value,
                Name = x.Element( "full-name" ).Value,
                Email = x.Descendants( "email-address" )
                            .Where( y => y.Element( "type" ).Value == "primary" )
                            .First().Element( "address" ).Value,
                JobTitle = x.Element( "job-title" ).Value,
                NetworkId = x.Element( "network-id" ).Value,
                Type = x.Element( "type" ).Value,
              } );

查询表达式并没有太大的区别:

var users = from response in xdoc.Descendants( "response" )
            where response.Element( "id" ) != null
            select new User
            {
                Id = response.Element( "id" ).Value,
                Name = response.Element( "full-name" ).Value,
                Email = response.Descendants( "email-address" )
                            .Where( x => x.Element( "type" ).Value == "primary" )
                            .First().Element( "address" ).Value,
                JobTitle = response.Element( "job-title" ).Value,
                NetworkId = response.Element( "network-id" ).Value,
                Type = response.Element( "type" ).Value
            };

1

像这样:

response.Descendants("email-address")
        .Single(a => a.Element("type").Value == "primary")
        .Element("address").Value

请注意,如果没有确切匹配的元素,这将抛出异常。
如果您不想这样做,请调用 FirstOrDefault
您可能希望使用 .Element("contact").Element("email-addresses").Element("email-address") 替换 .Descendants("email-address")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接