1

情况如下:

我有一个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”,还有“TotalSuperUberCoolTagThatHasADiferentNameLength”)

4

2 回答 2

2
XDocument xd = XDocument.Parse(xmlString);
var query = xd.Root.Elements("Total")
    .Descendants()
    .Where(x=>x.Name.LocalName.StartsWith("Total"));
于 2013-10-04T13:03:28.903 回答
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;
}
于 2013-10-04T13:06:10.870 回答