zoukankan      html  css  js  c++  java
  • Linq学习笔记---Linq to Xml操作

      LINQ to XML的成员,

      属性列表:

    属性 说明
    Document 获取此 XObject 的 XDocument
     EmptySequence  获取空的元素集合
     FirstAttribute  获取此元素的第一个属性
     FirstNode  获取此节点的第一个子节点
     HasAttributes  获取一个值,该值指示此元素是否至少具有一个属性
     HasElements  获取一个值,该值指示此元素是否至少具有一个子元素
     IsEmpty  获取一个值,该值指示此元素是否不包含内容
     LastAttribute  获取此元素的最后一个属性
     LastNode  获取此节点的最后一个子节点
     Name  获取或设置此元素的名称
     NextNode  获取此节点的下一个同级节点
     NodeType  获取此节点的节点类型
     Parent  获取此 XObject 的父级 XElement
     PreviousNode  获取此节点的上一个同级节点
     Value  获取或设置此元素的串连文本内容

      方法列表:

    方法 说明
    Add 将指定的内容添加为此 XContainer 的子级
    AddAfterSelf 紧跟在此节点之后添加指定的内容
    AddAnnotation 将对象添加到此 XObject 的批注列表
    AddBeforeSelf  紧邻此节点之前添加指定的内容
    AddFirst 将指定的内容作为此文档或元素的第一个子级添加
    Ancestors 返回此节点的上级元素的集合
    AncestorsAndSelf 返回元素集合,其中包含此元素及其上级
    Annotation 从此 XObject 获取指定类型的第一个批注对象
    Annotations 获取此 XObject 的指定类型的批注集合
    Attribute 返回具有指定 XName 的此 XElement 的 XAttribute
    Attributes 返回此元素的属性集合
    CreateReader 使用 readerOptions 参数指定的选项创建 XmlReader
    CreateWriter 创建可用于将节点添加至 XContainer 的 XmlWriter
    DescendantNodes 按文档顺序返回此文档或元素的子代节点集合
    DescendantNodesAndSelf 返回节点的集合,而这些节点包含此元素以及此元素的所有子代节点,并将它们按文档顺序排列
    Descendants 按文档顺序返回此文档或元素的子代元素集合
    DescendantsAndSelf 返回元素的集合,而这些元素包含此元素以及此元素的所有子代元素,并按文档顺序排列它们
    Elements 按文档顺序返回此元素或文档的经过筛选的子元素集合
    ElementsAfterSelf  按文档顺序返回此节点后的同级元素集合
    ElementsBeforeSelf  按文档顺序返回此节点前的同级元素集合
    GetDefaultNamespace  获取此 XElement 的默认 XNamespace
    GetNamespaceOfPrefix 获取此 XElement 的与特定前缀关联的命名空间
    GetPrefixOfNamespace 获取与此 XElement 的命名空间关联的前缀
    IsAfter  确定当前节点是否按文档顺序显示在指定节点之后
    IsBefore 确定当前节点是否按文档顺序显示在指定节点之前
    Load 从文件路径、TextReader、XmlReader、Stream中加载Xml数据
    Nodes 按文档顺序返回此元素或文档的子节点集合
    NodesAfterSelf 按文档顺序返回此节点后的同级节点的集合
    NodesBeforeSelf 按文档顺序返回此节点前的同级节点的集合
    Parse 从包含 XML 的字符串加载 XElement
    Remove 从节点父级中删除此节点
    RemoveAll 从此 XElement 中移除节点和属性
    RemoveAnnotations 从此 XObject 移除指定类型的批注 
    RemoveAttributes 移除此 XElement 的属性
    RemoveNodes 从此文档或元素中移除子节点
    ReplaceAll 使用指定的内容替换此元素的子节点和属性
    ReplaceAttributes 使用指定的内容替换此元素的属性
    ReplaceNodes 使用指定的内容替换此文档或元素的子节点
    ReplaceWith 使用指定的内容替换此节点
    Save 将此元素序列化为文件、XmlWriter、TextWriter、Stream
    SetAttributeValue 设置属性的值、添加属性或移除属性
    SetElementValue 设置子元素的值、添加子元素或移除子元素
    SetValue 设置此元素的值
    WriteTo 将此元素写入 XmlWriter

    二、LINQ to XML各种类的基本操作

      1、创建XML元素

      LINQ to XML使用XElement类创建XML元素。

      先来看一个最基本的示例:

    复制代码
        class Program
        {
            static void Main(string[] args)
            {
                XElement xml =
                    new XElement("Persons",
                        new XElement("Person",
                            new XElement("Name", "刘备"),
                            new XElement("Age", "28")
                            ),
                        new XElement("Person",
                            new XElement("Name", "关羽"),
                            new XElement("Age", "27")
                            )
                        );
                xml.Save(@"D:123.xml");
    
                Console.ReadKey();
            }
        }
    复制代码

      以上代码生成的XML文件代码如下:

    复制代码
    <?xml version="1.0" encoding="utf-8"?>
    <Persons>
      <Person>
        <Name>刘备</Name>
        <Age>28</Age>
      </Person>
      <Person>
        <Name>关羽</Name>
        <Age>27</Age>
      </Person>
    </Persons>
    复制代码

      非常简单的,下面给出一个非常全面的示例,包括XML大部分的节点类型。

    复制代码
        class Program
        {
            static void Main(string[] args)
            {
                //创建处理指令
                XProcessingInstruction instruction = new XProcessingInstruction("xml-stylesheet","href="hello.css" type = "text/css"");
                //创建声明对象
                XDeclaration xDeclaration = new XDeclaration("1.0","GB2312","yes");
                //创建文档类型
                XDocumentType documentType = new XDocumentType("Person", null, "Person.dtd", null);
                //创建XmlCData数据
                XCData data = new XCData("<h1>神奇的刘备</h1>");
                //创建XDocument文档
                XDocument xDoc = new XDocument();
                XElement xml =
                    new XElement("Persons",
                        new XElement("Person",
                            new XAttribute("Description", "此人龙凤之姿 天日之表;"),
                            new XElement("Name", data),
                            new XElement("Age", "28")
                            ),
                        new XElement("Person",
                            new XElement("Name", "关羽"),
                            new XElement("Age", "27")
                            )
                        );
                xDoc.Add(documentType);
                xDoc.Add(instruction);
                xDoc.Declaration = xDeclaration;
                xDoc.Add(xml);
                
                xDoc.Save(@"D:123.xml");
    
                Console.ReadKey();
            }
        }
    复制代码

      以上代码输出XML如下:

    复制代码
    <?xml version="1.0" encoding="gb2312" standalone="yes"?>
    <!DOCTYPE Person SYSTEM "Person.dtd">
    <?xml-stylesheet href="hello.css" type = "text/css"?>
    <Persons>
      <Person Description="此人龙凤之姿 天日之表;">
        <Name><![CDATA[<h1>神奇的刘备</h1>]]></Name>
        <Age>28</Age>
      </Person>
      <Person>
        <Name>关羽</Name>
        <Age>27</Age>
      </Person>
    </Persons>
    复制代码

      好用又简单。

    三、XML数据的输出

      XElement有个Save,这个Save非常强大,有多种重载,支持将XML数据输入到各处(文件地址,流,TextWriter,XmlWriter)。

    复制代码
        class Program
        {
            static void Main(string[] args)
            {
                XElement xml =
                    new XElement("Persons",
                        new XElement("Person",
                            new XElement("Name", "刘备"),
                            new XElement("Age", "28")
                            )
                        );
                //输出到文件
                xml.Save(@"D:123.xml");
                //输出到TextWriter
                TextWriter tw = new StringWriter();
                //第二个参数SaveOptions枚举支持设置格式,缩进,保留无关重要的空白,去除重复命名空间
                xml.Save(tw, SaveOptions.None);
                Console.WriteLine(tw);
                //输出到Stream
                using (MemoryStream mem = new MemoryStream())
                {
                    xml.Save(mem);
                    Console.WriteLine(Encoding.UTF8.GetString(mem.ToArray()));
                }
                //输出到XmlWriter
                XmlWriter xw = XmlWriter.Create(@"D:LinqToXml.xml");
                
                xml.Save(xw);
                xw.Flush();
                Console.ReadKey();
            }
        }
    复制代码

      一个DEMO完成输出到4个位置,不错。

    四、XML数据的输入

      1、从文件中输入XML数据

      XML数据的输出强大,XML数据的输入也同样强大,拥有多个重载的Load支持从URI,TextWriter,XmlReader输入XML数据。

    复制代码
            static void Main(string[] args)
            {
                //从URI中获取XML数据,支持本地路径和URL,支持对应枚举的设置
                XElement xe1 = XElement.Load(@"D:123.xml",LoadOptions.None);
                //从XmlReader中加载
                XmlReader xr = XmlReader.Create(@"D:123.xml");
                XElement xe2 = XElement.Load(xr);
                //从TextReader中获取数据
                TextReader reader = File.OpenText(@"D:123.xml");
                XElement xe3 = XElement.Load(reader);
                //从Stream中读取
                XElement xe4 = XElement.Load(new FileStream(@"D:123.xml",FileMode.Open,FileAccess.Read));
    
                Console.ReadKey();
            }
    复制代码

      2、从字符串中输入XML数据

      从字符串中解析数据为XML,只需要使用Parse方法。

    复制代码
            static void Main(string[] args)
            {
                string xmlString = "<?xml version="1.0" encoding="utf-8"?><Persons><Person><Name>刘备</Name><Age>28</Age></Person></Persons>";
                XElement xe = XElement.Parse(xmlString,LoadOptions.SetLineInfo);
    
                Console.ReadKey();
            }
    复制代码

      好用又简单

    五、XML基本查询

       基本查询更加简单,跟jQuery选择器差不多,链式操作。

    复制代码
            static void Main(string[] args)
            {
                string xmlString = "<?xml version="1.0" encoding="utf-8"?><Persons><Person Description="牛人"><Name>刘备</Name><Age>28</Age></Person></Persons>";
                XElement xe = XElement.Parse(xmlString,LoadOptions.SetLineInfo);
                //读取属性值
                string ArriValue = xe.Elements("Person").First().Attribute("Description").Value;
                //又或者
                //string ArriValue = xe.Element("Person").Attribute("Description").Value;
                Console.WriteLine(ArriValue);   //输出 牛人
    
                //读取元素  读取Name的后面的第一个兄弟元素
                XElement xe1 = xe.Element("Person").Element("Name").ElementsAfterSelf().First();
                Console.WriteLine(xe1.Value);   //输出 28
                //读取父节点
                XElement xe2 = xe1.Parent;
                Console.WriteLine(xe2.Name);
    
                Console.ReadKey();
            }
    复制代码

      其他查询:

    复制代码
            static void Main(string[] args)
            {
                string xmlString = "<?xml version="1.0" encoding="utf-8"?><Persons><Person Description="牛人"><Name>刘备</Name><Age>28</Age></Person><Person><Name>关羽</Name><Age>26</Age></Person></Persons>";
                XElement xe = XElement.Parse(xmlString, LoadOptions.SetLineInfo);
                //查询含有属性的Person节点
                List<XElement> ListElement = xe.Descendants("Person").Where(x => x.HasAttributes).ToList();
                foreach (XElement x in ListElement)
                {
                    Console.WriteLine(x.Value);     //输出 刘备28
                }
                //查询年龄为26的Person的Person节点
                List<XElement> ListElement2 = xe.Descendants("Person").Where(x => x.Element("Age").Value == "26").ToList();
                foreach (XElement x in ListElement2)
                {
                    Console.WriteLine(x.Value);     //输出 关羽26
                }
                Console.ReadKey();
            }
    复制代码

      Nodes、Descendants以及各自的AfterSelf用于转成IEnumerable<T>的LINQ查询。

    六、修改XML

       修改XML也非常简单,不再废话。直接给出简单示例:

    复制代码
            static void Main(string[] args)
            {
                string xmlString = "<?xml version="1.0" encoding="utf-8"?><Persons><Person Description="牛人"><Name>刘备</Name><Age>28</Age></Person></Persons>";
                XElement xe = XElement.Parse(xmlString, LoadOptions.SetLineInfo);
    
                //这是添加在最后,如果想添加在最前面可以使用AddFirst,
                //添加在本节点之前AddBeforSelf,添加在本节点之后AddAfterSelf
                xe.Add(new XElement("Person",
                            new XElement("Name", "关羽"),
                            new XElement("Age", 26)
                        )
                    );
                //删除所有子节点
                xe.RemoveAll();
    
                TextWriter tw = new StringWriter();
                //第二个参数SaveOptions枚举支持设置格式,缩进,保留无关重要的空白,去除重复命名空间
                xe.Save(tw, SaveOptions.None);
                Console.WriteLine(tw);
    
                Console.ReadKey();
            }
    复制代码
  • 相关阅读:
    C#GridViewExport帮助类,美化导出
    C#EXCEL 操作类--C#DataToExcel帮助类
    C#EXCEL 操作类--C#ExcelHelper操作类
    VS2010 项目引用了DLL文件,也写了Using,但是编译时提示:未能找到类型或命名空间名称 <转>
    FPGA Verilog HDL 系列实例--------步进电机驱动控制
    C++使用VARIANT实现二维数组的操作
    VS2010+VMWare8+VisualDDK1.5.6 创建并调试你的第一个驱动程序
    USB编程研究之二(常见设备类型的GUID)
    C++——CString用法大全
    C++ 如何有效地使用对话框
  • 原文地址:https://www.cnblogs.com/changrulin/p/4773361.html
Copyright © 2011-2022 走看看