最近在csdn上看到许多关于xml最基本的操作的贴子,也就是对一个xml文件进行,增加节点,更改节点值,读/改节点属性的值,读取xml,以便筛选出自已所需要的数据的这类需求,重复的很多。有的根本也没想到先去搜索一下看看有没有类似的操作。为了方便初学者或像我入门没多久的人方便查看,也省去了查询或提问的时间,我就在这献丑写了一个很简单的操作xml文件方法体,实现了对一xml文件读,修,增,删操作。当然这是最基本的操作。还有比较复杂的操作我们以后再讨论。
xml文件:
<?xml version="1.0" encoding="utf-8" ?>
<product>
<description>Updating</description>
<filelist count="1">
<item name="ASMIS.UI.exe" size="">
<value />
</item>
</filelist>
</product>
c#:
xml文件:
<?xml version="1.0" encoding="utf-8" ?>
<product>
<description>Updating</description>
<filelist count="1">
<item name="ASMIS.UI.exe" size="">
<value />
</item>
</filelist>
</product>
c#:
1
private void readxml()
2
{
3
XmlDocument doc = new XmlDocument();
4
doc.Load("XMLFile9.xml");
5
6
string nodetest = "";
7
XmlNode rootnode = doc.SelectSingleNode("//product");
8
if ( rootnode != null )
9
{
10
//更改节点属性值
11
XmlNode testnode = rootnode.SelectSingleNode("filelist");
12
XmlAttribute xa = testnode.Attributes["count"];
13
xa.InnerText = "2";
14
15
//更改节点值
16
XmlNode testnode1 = rootnode.SelectSingleNode("description");
17
if ( testnode1 != null)
18
testnode1.InnerText = "test";
19
20
//读取一节点
21
XmlNode testnode2 = rootnode.SelectSingleNode("description");
22
nodetest = testnode2.InnerText;
23
24
//增加一节点
25
XmlElement item2 = doc.CreateElement("item");
26
rootnode.AppendChild(item2);
27
28
//向节点添加属性
29
XmlAttribute xa = doc.CreateAttribute("name");
30
xa.InnerText="test2.dll";
31
item2.Attributes.Append(xa);
32
33
//删除一节点
34
XmlNode delnode = rootnode.SelectSingleNode("description");
35
rootnode.RemoveChild(delnode);
36
}
37
38
39
doc.Save("XMLFile9.xml");
40
41
}
private void readxml()2
{3
XmlDocument doc = new XmlDocument();4
doc.Load("XMLFile9.xml");5

6
string nodetest = "";7
XmlNode rootnode = doc.SelectSingleNode("//product");8
if ( rootnode != null )9
{10
//更改节点属性值11
XmlNode testnode = rootnode.SelectSingleNode("filelist");12
XmlAttribute xa = testnode.Attributes["count"];13
xa.InnerText = "2";14

15
//更改节点值16
XmlNode testnode1 = rootnode.SelectSingleNode("description");17
if ( testnode1 != null)18
testnode1.InnerText = "test";19

20
//读取一节点21
XmlNode testnode2 = rootnode.SelectSingleNode("description");22
nodetest = testnode2.InnerText;23

24
//增加一节点25
XmlElement item2 = doc.CreateElement("item");26
rootnode.AppendChild(item2);27

28
//向节点添加属性29
XmlAttribute xa = doc.CreateAttribute("name");30
xa.InnerText="test2.dll";31
item2.Attributes.Append(xa);32

33
//删除一节点34
XmlNode delnode = rootnode.SelectSingleNode("description");35
rootnode.RemoveChild(delnode);36
}37

38

39
doc.Save("XMLFile9.xml");40

41
}
浙公网安备 33010602011771号