选择元素的所有子元素

时间:2013-10-04 12:59:17

标签: c# xml linq

情况如下:

我有一个XDocument包含XML结构,如:

<report someatribute="smthin">
  <child></child>
  <othertypechild></othertypechild>

  ...etc...

  <Total>
    <Totalsum>totalsum</Totalsum>
    <Total1>sum1</Total1>
    <Total2>sum2</Total2>
    <Total3>sum3</Total3>
    <Total4>sum4</Total4>
    <Total5>sum5</Total5>
    <TimeFrom>...</TimeFrom>
    <Total6>...</Total6>        
  </Total>

  ....etc...

</report>

我想选择<Total>元素的所有子元素,其名称以“Total”开头。最好使用LINQ,但不一定。

编辑:我忘记了名字以“Total”开头的条件(如“Total6”,还有“TotalSuperUberCoolTagThatHasADifferentNameLength”)

2 个答案:

答案 0 :(得分:2)

XDocument xd = XDocument.Parse(xmlString);
var query = xd.Root.Elements("Total")
    .Descendants()
    .Where(x=>x.Name.LocalName.StartsWith("Total"));

答案 1 :(得分:0)

string s = @"<report>
                <child></child>
                <othertypechild></othertypechild>
                <Total>
                    <Totalsum>totalsum</Totalsum>
                    <Total1>sum1</Total1>
                    <Total2>sum2</Total2>
                    <Total3>sum3</Total3>
                    <Total4>sum4</Total4>
                    <Total5>sum5</Total5>        
                </Total>
            </report>";

XDocument doc = XDocument.Parse(s);

var total = doc.Descendants("Total");
var children = total.Descendants();

children将包含您要查找的元素。

编辑:这是一个更完整的示例,展示了如何从子项中获取值,并获得多个Total元素。

string s = @"<report>
                <child></child>
                <othertypechild></othertypechild>
                <Total>
                    <Totalsum>totalsum1</Totalsum>
                    <Total1>sum1.1</Total1>
                    <Total2>sum2.1</Total2>
                    <Total3>sum3.1</Total3>
                    <Total4>sum4.1</Total4>
                    <Total5>sum5.1</Total5>        
                </Total>

                <Total>
                    <Totalsum>totalsum2</Totalsum>
                    <Total1>sum1.2</Total1>
                    <Total2>sum2.2</Total2>
                    <Total3>sum3.2</Total3>
                    <Total4>sum4.2</Total4>
                    <Total5>sum5.2</Total5>        
                </Total>
            </report>";

XDocument doc = XDocument.Parse(s);

var totals = doc.Descendants("Total");

foreach (var total in totals)
{   
    var children = total.Descendants(); 
    children.Dump();

    var totalsum = children.Where(e => e.Name == "Totalsum").FirstOrDefault();
    var totalsunValue = totalsum != null ? totalsum.Value : null;
}