LINQ to XML

1、LINQ to XML经常使用成员

  LINQ to XML的成员,javascript

  属性列表:css

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

  方法列表:html

方法 说明
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

 

2、LINQ to XML各类类的基本操做

  一、建立XML元素java

  LINQ to XML使用XElement类建立XML元素。git

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

复制代码
    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文件代码以下:post

复制代码
<?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以下:this

复制代码
<?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>
复制代码

  好用又简单。spa

3、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个位置,不错。

4、XML数据的输入

  一、从文件中输入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();
        }
复制代码

  二、从字符串中输入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();
        }
复制代码

  好用又简单

5、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查询。

6、修改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();
        }
复制代码

 

 

 
 
 
0
0
 
(请您对文章作出评价)
 
« 上一篇: Xml序列化
» 下一篇: TextReader/TextWriter 的类