zoukankan      html  css  js  c++  java
  • 在XML文档中替换元素名称的做法

    不要小看这个操作,其实是不太容易的。请注意,我们是要替换掉元素的名称,而不是元素的值。

    XML的内容在内存中是一个DOM树,要替换掉一个元素,其实是要新建一个元素,并且将原先元素的所有子元素都复制过来。在LINQ TO XML中用ReplaceWith来实现

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

    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                XDocument doc = new XDocument(
                    new XElement("Tables"
                        , new XElement("Table"
                            , new XElement("Name", "Orders")
                            , new XElement("Owner", "chenxizhang"))
                        , new XElement("Table"
                            , new XElement("Name", "Customers")
                            , new XElement("Owner", "Allen"))
                        ));
                Console.WriteLine("原始的XML内容:");
                Console.WriteLine(doc);

                //改变Tables元素名称为Items
                Console.WriteLine("改变了根元素之后显示的效果:");
                XElement root = doc.Element("Tables");
                root.ReplaceWith(new XElement("Items", root.Elements("Table")));
                Console.WriteLine(doc);

                //改变Table元素名称为Item

                Console.WriteLine("改变了子元素之后显示的效果:");
                foreach (var item in doc.Elements("Items").Descendants().ToList())//这里一定要先ToList
                {
                    item.ReplaceWith(new XElement("Item", item.Descendants()));
                }
                Console.WriteLine(doc);

                Console.Read();
            }
        }
    }

     

    image

  • 相关阅读:
    Shell编程学习1-变量的高级用法
    Ubuntu新机配置深度学习环境遇到的问题
    Python细致技巧总结(不断更新)
    图片着色后存储为“JPEG”格式存在明显色差问题解决
    python图片合成视频
    caffe-ssd安装问题解决
    python画图
    python split(),os.path.split()和os.path.splitext()函数用法
    转载:mysql 存储过程
    css实现div框阴影
  • 原文地址:https://www.cnblogs.com/chenxizhang/p/1489277.html
Copyright © 2011-2022 走看看