• linq xml 转


    本文介绍如何使用 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

  • 相关阅读:
    .Net常见笔试题
    冒泡排序算法 C#版
    Bundle捆绑压缩技术
    异步Ajax
    HtmlHelper总结
    HtmlHelper的扩展分页方法
    WCF
    程序猿值得看的几个技术网站(记录)
    Struts2和SpringMVC的区别
    nginx配置文件作用介绍
  • 原文地址:https://www.cnblogs.com/eebb/p/1166208.html
Copyright © 2020-2023  润新知