1、常用到的类
private static void Xml() { XDocument xml = new XDocument();//描述会自动创建 Encoding为UTF-8 XDeclaration dec=new XDeclaration("1.0","UTF-8","yes"); XNamespace xmln = "SB-GAVIN-AA";//添加xml命名空间,xmlns XNamespace xm = "GAVIN-AA"; XElement eleHead = new XElement(xmln + "Head");//创建节点,并声明该节点的命名空间为xmln XElement eleDetail = new XElement("name");//创建节点,若前面有声明过命名空间,不会默认继承,会添加 xmlns = "" XElement ele = new XElement(xm + "column");//创建节点,每个节点的命名空间可以不同 XAttribute appearance = new XAttribute("appearance", "nice"); //创建属性 XAttribute name = new XAttribute("name", "Hao"); //创建属性 xml.Add(eleHead); //添加根节点 eleHead.Add(eleDetail); //添加子节点 eleDetail.Add(ele); //添加子节点 eleDetail.Add(appearance); //子节点添加属性 xml.Save("3.xml"); //保存文件,保存路径在Debug目录下 }
1
2
3
4
5
6
|
<?xml version= "1.0" encoding= "utf-8" ?> <Head xmlns= "SB-GAVIN-AA" > <name appearance= "nice" xmlns= "" > <column xmlns= "GAVIN-AA" /> </name> </Head> |
private static void LoadXml() { XDocument xdoc = XDocument.Load(@"..\Debug\xml\3.xml");//.. -------> .....\bin\ List<XElement> ele = new List<XElement>(); string Apprearance = "nice"; XNamespace xmln = "SB-GAVIN-AA"; XNamespace xm = "GAVIN-AA"; XElement e = xdoc.Element(xmln + "Head");//元素含有xmlns时,添加XNamespace来定位节点。没有xmlns则不用添加XNamespace foreach (XElement item in e.Elements()) { //判断这个元素的名字是不是name,如果是name,看内容是不是nameTxt if (item.Name.LocalName == "name") { if (item.Attribute("appearance").Value == Apprearance) { //符合条件的节点,取其父级 ele.Add(item.Parent); } } } foreach (XElement item in ele) { Console.WriteLine("appearance:{0}", item.Element("name").Attribute("appearance").Value); //输出结果:appearance:nice } Console.ReadKey(); }
4、XML节点的删改
(删)原xml文件:
<?xml version="1.0" encoding="utf-8"?> <Head> <name appearance="nice"> <column name="Hao" /> </name> <column /> </Head>
private static void RemoveXml() { XDocument xdoc = XDocument.Load(@"..\Debug\xml\4.xml"); XElement e = xdoc.Element("Head");//定位节点Head foreach (XElement xxElement in e.Elements()) { if (xxElement.Name.LocalName == "column") { xxElement.Remove();//删除根节点Head里的子节点column xdoc.Save(@"..\Debug\xml\4.xml");//保存修改 } } Console.ReadKey(); } }
删减后:
<?xml version="1.0" encoding="utf-8"?> <Head> <name appearance="nice"> <column name="Hao" /> </name> </Head>
(改)
private static void updateXml() { XDocument xdoc = XDocument.Load(@"..\Debug\xml\4.xml"); XElement e = xdoc.Element("Head"); string att = "supnice"; string name = "Hao"; foreach (XElement xxElement in e.Elements()) { if (xxElement.Name.LocalName == "name") { xxElement.Name = name;//修改节点名字 xxElement.Attribute("appearance").Value = att;//修改appearance的属性为supnice xdoc.Save(@"..\Debug\xml\4.xml");//保存修改 } } }
下载说明
☉本站所有源码和资源均由站长亲自测试-绝对保证都可以架设,运营!
☉如源码和资源有损坏或所有链接均不能下载,请告知管理员,
☉本站软件和源码大部分为站长独资,资源购买和收集,放心下载!
☉唯一站长QQ:1004003180 [人格担保-本站注重诚信!]
☉购买建议E-mail:1004003180@qq.com 源码收购 E-mail:1004003180@qq.com
☉本站文件解压密码 【文章内都自带解压密码,每个密码不同!】