Linq to xml - XDocument - 如何读取嵌套节点

时间:2013-11-30 18:12:21

标签: nested linq-to-xml

我有xml以下,我的目标是给定ProductName(例如Spot)和给定语言例如(“en-gb”)我想要所有翻译。所以在这种情况下(ProductName = Spot和language =“en-gb”)输出应该是TRADE STATUS,TRADE ID,VALUE DATE

我在linq查询下面尝试了但它打印了“ProductType = Spot”的所有翻译,而不是ProductType = Spot和language =“en-gb”的所有翻译

    var qry = doc.Descendants("Product")
    .Where(p => p.Attribute("ProductName").Value == "Spot")
    .Where(p =>   
   p.Element("Fields")
 .Element("Field")
.Element("Translations")
.Element("Translation")
.Attribute("language")
.Value == "en-gb")
.Select(p => new { Text = p.Value });

如果有人可以为上述目标建议linq查询,那将会很棒。

<?xml version="1.0" encoding="utf-8" ?>
<Products>
  <Product ProductName="Spot">
    <Fields>
      <Field FieldName="tradeStatus">
        <Translations>
          <Translation language="en-gb">TRADE STATUS</Translation>
          <Translation language="fr-fr">fr_TRADE STATUS</Translation>
          <Translation language="cz-cz">cz_TRADE STATUS</Translation>
        </Translations>
      </Field>
      <Field FieldName="tradeId">
        <Translations>
          <Translation language="en-gb">TRADE ID</Translation>
          <Translation language="fr-fr">fr_TRADEid</Translation>
          <Translation language="cz-cz">cz_TRADEid</Translation>
        </Translations>
      </Field>    
      <Field FieldName="valueDate">
        <Translations>
          <Translation language="en-gb">VALUE DATE</Translation>
          <Translation language="fr-fr">fr_ValueDate</Translation>
          <Translation language="cz-cz">cz_ValueDt</Translation>
        </Translations>
      </Field>    
    </Fields>
  </Product>
  <Product ProductName="Forward">
    <Fields>
      <Field FieldName="dealtRate">
        <Translations>
          <Translation language="en-gb">DEALT RATE</Translation>
          <Translation language="fr-fr">fr_dealtrt</Translation>
          <Translation language="cz-cz">cz_dr</Translation>
        </Translations>
      </Field>
      <Field FieldName="dealtAmount">
        <Translations>
          <Translation language="en-gb">DEALT AMOUNT</Translation>
          <Translation language="fr-fr">fr_dAmtt</Translation>
          <Translation language="cz-cz">cz_dealtAmtt</Translation>
        </Translations>
      </Field>      
    </Fields>
  </Product>

</Products>

1 个答案:

答案 0 :(得分:0)

我找到了自己问题的答案,在linq查询工作下面

var qry = doc.Descendants("Product")
    .Where(p=>p.Attribute("ProductName").Value=="Spot").Descendants("Fields").Descendants("Translations").Descendants("Translation")
    .Where(t => t.Attribute("language").Value == "en-gb")
    .Select(t => new { Text = t.Value });