使用XDocument遍历节点的所有属性 [英] Loop through all the attributes of a node using XDocument

查看:89
本文介绍了使用XDocument遍历节点的所有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

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

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>

我正在尝试通过以下方式实现这一目标:(根据Henk的建议编辑)

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?

推荐答案

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

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())
   ...

这篇关于使用XDocument遍历节点的所有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆