C#4.0:删除XML文件的所有节点 [英] C#4.0: To delete all nodes of an XML file

查看:422
本文介绍了C#4.0:删除XML文件的所有节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello


我有一个XML文件:

<?xml version =" 1.0" ;编码= QUOT; UTF-8英寸?> 
- < dataroot xmlns:od =" urn:schemas-microsoft-com:officedata"的xmlns:的xsi = QUOT; HTTP://www.w3.org/2001/XMLSchema-instance"的xsi:noNamespaceSchemaLocation = QUOT; Test.xsd"产生= QUOT; 2016-09-16T22:06:41">
- < Table2>
< ID> 1< / ID>
< Name> A< / Name>
< / Table2>
- < Table2>
< ID> 2< / ID>
< Name> B< / Name>
< / Table2>
< / dataroot>


我想删除所有节点。


解决方案

我写了这段代码。这有效:

 XmlDocument xmlDoc = new XmlDocument(); 
xmlDoc.Load(Application.StartupPath + @" \ Table1.xml");
XmlElement xmlRoot = xmlDoc.DocumentElement;
XmlNodeList Types = xmlRoot.ChildNodes;
int countTypes = Types.Count;
int index = 0;
while(index< countTypes)
{
XmlNode nodelist = xmlDoc.SelectSingleNode(" / dataroot / Table1 [ID ='" +(index + 1).ToString()+ "']");
nodelist.ParentNode.RemoveChild(nodelist);
index ++;
}
xmlDoc.Save(Application.StartupPath + @" \ Table1.xml");


Hello

I have an XML file:

 <?xml version="1.0" encoding="UTF-8" ?> 
- <dataroot xmlns:od="urn:schemas-microsoft-com:officedata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Test.xsd" generated="2016-09-16T22:06:41">
- <Table2>
  <ID>1</ID> 
  <Name>A</Name> 
  </Table2>
- <Table2>
  <ID>2</ID> 
  <Name>B</Name> 
  </Table2>
  </dataroot>

I want to delete all of nodes.

解决方案

I wrote this code. This works weel:

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(Application.StartupPath + @"\Table1.xml");
                XmlElement xmlRoot = xmlDoc.DocumentElement;
                XmlNodeList Types = xmlRoot.ChildNodes;
                int countTypes = Types.Count;
                int index = 0;
                while (index < countTypes)
                {
                    XmlNode nodelist = xmlDoc.SelectSingleNode("/dataroot/Table1[ID='" + (index + 1).ToString() + "']");
                    nodelist.ParentNode.RemoveChild(nodelist);
                    index++;
                }
                xmlDoc.Save(Application.StartupPath + @"\Table1.xml");


这篇关于C#4.0:删除XML文件的所有节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆