zoukankan      html  css  js  c++  java
  • Linq to Xml (1) 创建和查询包含命名空间的XML文档

    在项目实施中,我们常常会使用XML作为配置文件,对于普通(不包含命名空间)的XML文档,使用Linq可以很方便地进行读写操作。而对于含有命名空间的XML文档,查询时则需要指定元素所在的命名空间,才能准确获取到结点值。

    示例一:下面我使用Linq创建一个包含一个默认命名空间的XML文档:

    // 创建含有默认命名空间的Xml文档    
    XDocument xDoc=new XDocument();
    XDeclaration xDeclar=new XDeclaration("1.0","utf-8","yes");
    xDoc.Declaration=xDeclar;
    XNamespace xns="http://www.netbrother.net";
    XElement root=new XElement(xns+"Root",new XElement(xns+"SmartCoder","Tiramisu"));
    xDoc.Add(root);
    Console.WriteLine(xDoc.Declaration.ToString());
    Console.WriteLine(xDoc);

    示例中使用字符串对XNamespace赋值,我想大家已经猜到了,在XNamespace的实现中,使用了隐式转换。这里我添加了一个默认的命名空间 xns,示例输出结果如下:

    <?xml version="1.0" encoding="utf-8" standalone="yes"?>
    <Root xmlns="http://www.netbrother.net">
      <SmartCoder>Tiramisu</SmartCoder>
    </Root> 

    示例二:我们还可以通过使用别名的方式,来为XML文档指定多个命名空间。下面是一个包含多个命名空间的示例:

    // 创建含有多个命名空间的Xml文档    
    XDocument xDoc = new XDocument();
    XDeclaration xDeclar = new XDeclaration("1.0","utf-8","yes");
    xDoc.Declaration = xDeclar;    
    XNamespace nbNamespace = "http://www.netbrother.net";
    XNamespace cuNamespace = "http://www.codeunion.net";
    XElement root= new XElement(cuNamespace+"Root",
        new XAttribute(XNamespace.Xmlns + "nb",nbNamespace),
        new XAttribute(XNamespace.Xmlns + "cu",cuNamespace),
        new XElement(cuNamespace + "SmartCoder",
            new XElement(nbNamespace + "Coder","Tiramisu"),
            new XElement(nbNamespace + "GF","GY")),        
        new XElement(cuNamespace + "SmartCoder",
            new XElement(nbNamespace + "Coder","CD"),
            new XElement(nbNamespace + "GF","XL")));
    xDoc.Add(root);
    Console.WriteLine(xDoc.Declaration.ToString());
    Console.WriteLine(xDoc);

    此示例中,我声明了两个命名空间对象(cuNamespace和nbNamespace),并将它们追加到 Xmlns 默认命名空间来声明别名(命名空间前缀)。示例中,SmartCoder元素位于cuNamespace命名空间,而其子元素 Coder 和 GF 位于nbNamespace命名空间。此示例输出结果如下:

    <?xml version="1.0" encoding="utf-8" standalone="yes"?>
    <cu:Root xmlns:nb="http://www.netbrother.net" xmlns:cu="http://www.codeunion.net">
      <cu:SmartCoder>
        <nb:Coder>Tiramisu</nb:Coder>
        <nb:GF>MM</nb:GF>
      </cu:SmartCoder>
      <cu:SmartCoder>
        <nb:Coder>CD</nb:Coder>
        <nb:GF>XL</nb:GF>
      </cu:SmartCoder>
    </cu:Root>

    下面我们对示例二中的文档进行检索:

    // 检索含有命名空间的Xml文档
    var smartCoder=xDoc.Descendants(cuNamespace+"SmartCoder").Elements(nbNamespace+"Coder").First();
    var gf=smartCoder.Parent.Element(nbNamespace+"GF");
    Console.WriteLine(smartCoder.Value);
    Console.WriteLine(gf.Value);

    检索输出结果如下:

    Tiramisu
    GY

  • 相关阅读:
    命令模式
    软件设计师_例题
    软件设计师_计算机系统基础(1.1)
    ForkJoin之ForkJoinTask框架学习笔记
    Oracle使用语句块之循环插入数据
    SpringCloud搭建分布式配置中心(基于git)
    Docker配置JDK1.8
    Linux命令查看文件内容
    Mac配置maven环境命令
    Docker安装mysql8
  • 原文地址:https://www.cnblogs.com/gb2013/p/2663283.html
Copyright © 2011-2022 走看看