Home > Backend Development > XML/RSS Tutorial > Detailed explanation of how to replace element names in XML documents (picture)

Detailed explanation of how to replace element names in XML documents (picture)

黄舟
Release: 2017-03-24 17:17:35
Original
2391 people have browsed it

Don’t underestimate this operation, it is actually not easy. Note that we are replacing the element's name, not its value. The content of

XML is a DOM tree in memory. To replace an element, you actually need to create a new element and copy all the child elements of the original element. Using ReplaceWith in LINQ TO XML

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

Detailed explanation of how to replace element names in XML documents (picture)

The above is the detailed content of Detailed explanation of how to replace element names in XML documents (picture). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template