Linq to XML 根据属性值遍历子节点


ContractedBlock.gif ExpandedBlockStart.gif Code
<?xml version="1.0" encoding="utf-8" ?>
<Cards>
    
<CardsClass cardclassID="10000" text="费用卡">
        
<item itemID="10001" text="月卡"></item>
        
<item itemID="10002" text="季卡"></item>
        
<item itemID="10003" text="次卡"></item>
        
<item itemID="10004" text="终身卡"></item>
    
</CardsClass>
    
<CardsClass cardclassID="30000" text="团体卡">
        
<item itemID="30001" text="家庭卡"></item>
        
<item itemID="30002" text="情侣卡"></item>
        
<item itemID="30003" text="公司卡"></item>
    
</CardsClass>
    
<CardsClass cardclassID="40000" text="VIP卡">
        
<item itemID="40001" text="VIP卡"></item>
    
</CardsClass>
</Cards>
ContractedBlock.gif ExpandedBlockStart.gif Code
string strXmlPath = System.Web.HttpContext.Current.Server.MapPath("Stadium_card.xml");
        XElement xml 
= XElement.Load(strXmlPath);

/*方法1*/
        
//var a = from b in xml.Descendants("item")
        
//        where b.Attribute("itemID").Value.Substring(0, 2) == "10"
        
//        select new { itemID = b.Attribute("itemID").Value, itemName = b.Attribute("text").Value };

/*方法2*/

        var a
=from b in xml.Descendants("item")
               
where b.Parent.Attribute("cardclassID").Value=="10000"
               select 
new { itemID = b.Attribute("itemID").Value, itemName = b.Attribute("text").Value };

        
foreach (var n in a)
        {
            ListItem item 
= new ListItem(n.itemName, n.itemID);
        }

转载于:https://www.cnblogs.com/flysnow-z/archive/2009/03/23/1419514.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值