Linq to xml读取属性

代码
<?xml version="1.0" encoding="utf-8" ?>
<China>
  
<Province ProvinceSpelling="yue_guangdong" ChineseName="广东" Url ="http://gz.club.99pet.com/ClubArticle/ClubAritcleList.aspx?city=gd">
    
<CityFlag CitySpelling="guangzhou"  ChineseName="广州">GuangzhouPeripheral</CityFlag>
    
<CityFlag CitySpelling="foshan"  ChineseName="佛山">GuangzhouPeripheral</CityFlag>
    
<CityFlag CitySpelling="zhongshan"  ChineseName="中山">GuangzhouPeripheral</CityFlag>
    
<CityFlag CitySpelling="dongguan"  ChineseName="东莞">GuangzhouPeripheral</CityFlag>
    
<CityFlag CitySpelling="zhaoqing"  ChineseName="肇庆">GuangzhouPeripheral</CityFlag>
    
<CityFlag CitySpelling="shaoguan"  ChineseName="韶关">GuangzhouPeripheral</CityFlag>
    
<CityFlag CitySpelling="shenzhen"  ChineseName="深圳">GuangzhouPeripheral</CityFlag>
  
</Province>
  
<Province ProvinceSpelling="jing_beijing" ChineseName="北京"  Url ="http://bj.club.99pet.com/ClubArticle/ClubAritcleList.aspx?city=beijing">
    
<CityFlag CitySpelling="beijing"  ChineseName="北京">beijingPeripheral</CityFlag>
  
</Province>
  
<Province ProvinceSpelling="lu_shanghai" ChineseName="上海"  Url ="http://sh.club.99pet.com/ClubArticle/ClubAritcleList.aspx">
    
<CityFlag CitySpelling="shanghai"  ChineseName="上海">shanghaiPeripheral</CityFlag>
  
</Province>
  
<Province ProvinceSpelling="jing_tianjing" ChineseName="天津"  Url ="http://tj.club.99pet.com/ClubArticle/ClubAritcleList.aspx">
    
<CityFlag CitySpelling="tianjing"  ChineseName="天津">tianjingPeripheral</CityFlag>
  
</Province>
</China>

xml文件如上。现在是如何查询和读取里面的字段。

代码如下:这里显示了2个特性。第一是XElement是Xml里面的元素,第二是Attribute是元素里面的属性。Linq查询返回的是IEnumerable接口。Attribute是个键值对关系的属性。通常我们取的是元素某属性的值

代码
 private string _name;
        
protected void Page_Load(object sender, EventArgs e)
        {

        }

        
private void bindXml()
        {
            
string xmlUrl = "PeripheralFlag.xml";

            XElement root 
= XElement.Load(Server.MapPath(xmlUrl));
            IEnumerable attribNames 
= from el in root.Elements("Province")
                                      
where el.Attribute("ChineseName").Value.Equals(txtInput.Text.Trim())
                                      select el;
            
foreach (XElement attribName in attribNames)
            {
                _name 
= attribName.Attribute("Url").Value;
                lbResult.Text 
+= _name;
            }
        }

        
protected void btnSumbit_Click(object sender, EventArgs e)
        {
            lbResult.Text 
= "";
            bindXml();
        }
    }

 

 

posted @ 2010-05-05 01:22  Drek  阅读(645)  评论(0)    收藏  举报