Loop through all the attributes of a node using XD

2020-07-25 12:17发布

问题:

I have the following xml that stores table definations. How can I loop through each column of the passed tablename (only one occurrence of each table) and their attributes using XDocument (C# 3.5)

Ex: If user passes CurrencySummary, I want to read each column and all it's attributes like HeaderDescription, HeaderName etc.

<?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>

I am trying to achieve this by: (edited: as per Henk's suggestion)

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
    }
}

Is this is efficient way or if there is anything better than this?

回答1:

It depends a little on how many <CurrencySummary>s there are and if their place matters.

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

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


回答2:

EDIT OP not on .Net 4, so not using SelectMany, if Single() not .Net 4.0 substitute with First()

Looks like you there should be only one "CurrencySummary" so ...

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

Will iterate through all the attributes of all the elements in the one and only CurrencySummary element, anywhere in the TableDefninations.xml.