Home >Backend Development >XML/RSS Tutorial >Detailed explanation of how to replace element names in XML documents (picture)
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(); } } }
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!