查看文章
 
linq与xml
2008年11月14日 星期五 14:50

本文介绍如何使用 Descendants、Elements快速遍历XML节点

首先准备一个简单但是常见的XML
<?xml version="1.0" encoding="utf-8" ?>
<userSet>
<userInfo id="1" name="Guozhijian">
    <profile>
      <phoneNumber>13818181818</phoneNumber>
      <country>China</country>
    </profile>
</userInfo>
<userInfo id="2" name="Zhenglanzhen">
    <profile>
      <phoneNumber>13919191919</phoneNumber>
      <country>Korea</country>
    </profile>
</userInfo>
</userSet>

<?xml version="1.0" encoding="utf-8" ?>
<userSet>
<userInfo id="1" name="Guozhijian">
    <profile>
      <phoneNumber>13818181818</phoneNumber>
      <country>China</country>
    </profile>
</userInfo>
<userInfo id="2" name="Zhenglanzhen">
    <profile>
      <phoneNumber>13919191919</phoneNumber>
      <country>Korea</country>
    </profile>
</userInfo>
</userSet>
测试一:
private void Test1()
{
    XDocument xdoc = XDocument.Load(@"UserSet.xml");
    var users = from u in xdoc.Descendants("userInfo")
                where u.Attribute("id").Value == "1"
                select u;
    foreach (var u in users)
    {
        string name = u.Attribute("name").Value;
        Console.WriteLine(name);
    }
}
输出结果为:
Guozhijian

测试二
private void Test2()
{
    XDocument xdoc = XDocument.Load(@"UserSet.xml");
    var users = from u in xdoc.Root.Elements("userInfo")
                where u.Element("profile").Element("phoneNumber").Value == "13919191919"
                select u;
    foreach (var u in users)
    {
        string name = u.Attribute("name").Value;
        Console.WriteLine(name);
    }
}
输出结果为:
Zhenglanzhen


类别:c#3.0(3.5)||添加到搜藏 |分享到i贴吧|浏览(344)|评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
     

   
帮助中心 | 空间客服 | 投诉中心 | 空间协议
©2012 Baidu