zoukankan      html  css  js  c++  java
  • Linq to XML 读取XML 备忘笔记

    最近一个项目中有要用到 xml 读取,我首先想到的是使用 Linq 读取(XML 解析感觉有点麻烦),项目完成,现抽取其内容,作如下笔记备忘.

    1. demo.xml

    demo.xml
    <?xml version="1.0" encoding="utf-8" ?>
    <note>
      
    <conf>
        
    <to>infozero</to>
        
    <from>lerroy</from>
        
    <heading>测试信息</heading>
        
    <body>第一条测试信息</body>
        
    <title name="我的第一条消息">from myself</title>
      
    </conf>
      
    <conf>
        
    <to>infozero@163.com</to>
        
    <from>text</from>
        
    <heading> 时刻提醒我 </heading>
        
    <body>这是一条测试信息!</body>
        
    <title name="我的第二条消息">from others</title>
      
    </conf>
    </note>

    2.在 程序中引用以下命名空间:

    using System;
    using System.Linq;
    using System.Xml.Linq;

    3.读取方法如下:


    main 函数入口
        class Program
        {
            
    static void Main(string[] args)
            {
                XDocument doc 
    = XDocument.Load("demo.xml");
                var text 
    = from t in doc.Descendants("conf")                    //定位到节点 
                           .Where(w => w.Element("to").Value.Contains('@'))   //若要筛选就用上这个语句 
                           select new
                           {
                               to 
    = t.Element("to").Value,
                               froms 
    = t.Element("from").Value,
                               head 
    = t.Element("heading").Value,
                               body 
    = t.Element("body").Value,
                               title 
    = t.Element("title").Attribute("name").Value   //注意此处用到 attribute 
                           };
                
    foreach (var a in text)
                {
                    Console.WriteLine(a.to);
                    Console.WriteLine(a.froms);
                    Console.WriteLine(a.head);
                    Console.WriteLine(a.body);
                    Console.WriteLine(a.title);
                }
                Console.ReadKey();
            }
        }


    结果:

     

    小结: Linq to Xml 确实是个好东西 ,它极大地方便了我们的编程。

    ---------- 后续补充:-----

    另外一种 XML 格式 的解析参见:  http://www.cnblogs.com/portalsky/archive/2008/09/11/1289461.html 
    XML 增删改查: http://www.cnblogs.com/greatverve/archive/2010/07/13/linq-to-xml-one-begin.html

  • 相关阅读:
    The test form is only available for requests from the local machine
    64位Win7下,先安装Visual Studio,后安装IIS的设置步骤
    [转] 如何在 64 位的 Windows 7 中安裝 PLSQL DEVELOPER 8 和 Oracle 11g x64 Client
    excel对csv的转义
    js中没有引用的匿名函数调用方法
    缓存实现条件
    js对象成员的删除特性 (delete)
    js语法作用域之间的相关性
    【转】UBOOT之四:uboot.lds分析
    linux C 中的volatile使用
  • 原文地址:https://www.cnblogs.com/infozero/p/1776383.html
Copyright © 2011-2022 走看看