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();
}
}
}
以上就是详解在XML文档中替换元素名称的方法(图)的详细内容,更多请关注php中文网其它相关文章!
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
程序员必备接口测试调试工具:点击使用
Apipost = Postman + Swagger + Mock + Jmeter
Api设计、调试、文档、自动化测试工具
网页生成APP,用做网站的技术去做APP:立即创建
手机网站开发APP、自助封装APP、200+原生模块、2000+映射JS接口按需打包
相关文章
相关视频