详解在XML文档中替换元素名称的方法(图)

黄舟
黄舟 原创
2017-03-24 17:17:35 1938浏览

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

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();
        }
    }
}

1279.png

以上就是详解在XML文档中替换元素名称的方法(图)的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。