使用XDocument遍历节点的所有属性

时间:2011-06-06 14:31:18

标签: c# xml linq .net-3.5 linq-to-xml

我有以下用于存储表格定义的xml。如何使用XDocument(C#3.5)遍历传递的tablename的每一列(每个表只出现一次)及其属性

Ex:如果用户通过CurrencySummary,我想读取每一列及其所有属性,如HeaderDescription,HeaderName等。

<?xml version="1.0" encoding="utf-8" ?>
<TableDef>
  <CurrencySummary>
    <Column Name="Currency" HeaderDescription="Currency" HeaderName="Currency" ColumnType="TableColumnType.Text" IsHidden = "false" Position="0" Width="100" />
    <Column Name="ParamortizedValue" HeaderDescription="Par/amortized value" HeaderName="paramortizedvalue" ColumnType="TableColumnType.Number" IsHidden = "false" Position="1" Width="200" />
    <Column Name="PercentBondTotal" HeaderDescription="% of bond total" HeaderName="percentbondtotal" ColumnType="TableColumnType.Number" IsHidden = "false" Position="2" Width="150" />
  </CurrencySummary>
  <CallSchedule>
    <Column Name="Calldate" HeaderDescription="Call date" HeaderName="Calldate" ColumnType="TableColumnType.Text" IsHidden = "false" Position="0" Width="100" />
    <Column Name="Issue" HeaderDescription="Issue" HeaderName="Issue" ColumnType="TableColumnType.Text" IsHidden = "false" Position="1" Width="100" />
    <Column Name="ParamortizedValue" HeaderDescription="Par/amortized value" HeaderName="paramortizedvalue" ColumnType="TableColumnType.Number" IsHidden = "false" Position="2" Width="200" />
    <Column Name="PercentBondTotal" HeaderDescription="% of bond total" HeaderName="percentbondtotal" ColumnType="TableColumnType.Number" IsHidden = "false" Position="3" Width="150" />
  </CallSchedule>
</TableDef>

我试图通过以下方式实现:(编辑:根据Henk的建议)

var doc = XDocument.Load("TableDefinations.xml");
var cols = doc.Descendants("CurrencySummary").First();
foreach (var col in cols.Elements())
{
    foreach (XAttribute at in col.Attributes())
    {
        //do something with the at.Name and at.Value
    }
}

这是有效的方式还是有什么比这更好的?

2 个答案:

答案 0 :(得分:5)

这取决于有多少<CurrencySummary>,以及它们的位置是否重要。

var summ = doc.Descendants("CurrencySummary").First();

foreach (var col in summ.Elements())
   ...

答案 1 :(得分:5)

编辑 OP不在.Net 4上,所以不使用SelectMany,如果Single()没有.Net 4.0替换为First()

看起来你应该只有一个"CurrencySummary"所以......

var doc = XDocument.Load("TableDefinations.xml");
foreach(XElement col in doc.Descendants("CurrencySummary").Single().Elements())
{
    foreach(XAttribute at in col.Attributes())
    {
        at...
    }
}

将迭代遍历TableDefninations.xml中任何位置的唯一CurrencySummary元素中所有元素的所有属性。