欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C# 對(duì)XML基本操作代碼總結(jié)

 更新時(shí)間:2011年10月10日 19:38:05   作者:  
C# 對(duì)XML基本操作包括讀取節(jié)點(diǎn)的數(shù)據(jù),添加節(jié)點(diǎn)。讀取節(jié)點(diǎn)屬性,修改節(jié)點(diǎn)屬性等
具體如下:
XML文件:文件在MyDocument文件夾下
復(fù)制代碼 代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<PersonF xmlns="" Name="(test)work hard work smart!">
<person Name="Person1">
<ID>1</ID>
<Name>XiaoA</Name>
<Age>59</Age>
</person>
<person Name="Person2">
<ID>2</ID>
<Name>XiaoB</Name>
<Age>29</Age>
</person>
<person Name="Person3">
<ID>3</ID>
<Name>XiaoC</Name>
<Age>103</Age>
</person>
<person Name="Person4">
<ID>4</ID>
<Name>XiaoD</Name>
<Age>59</Age>
</person>
</PersonF>

Code:說明都在注釋里。
復(fù)制代碼 代碼如下:

void TestXML()
{
XmlDocument doc = new XmlDocument();
string path = "http://www.dbjr.com.cn/MyDocument/Person.xml";
try
{
doc.Load(path);
//1、讀取單個(gè)節(jié)點(diǎn)的數(shù)據(jù)
XmlNode node = doc.SelectSingleNode("PersonF");
//2、讀取多個(gè)節(jié)點(diǎn)的數(shù)據(jù)
XmlNodeList nodeList1 = doc.SelectNodes("PersonF/person");
//3.1 讀取具體節(jié)點(diǎn)的具體值 如:屬性為Person2的第二個(gè)節(jié)點(diǎn)Name的InnerText
XmlNodeList nodeList = doc.DocumentElement.GetElementsByTagName("person");
foreach (XmlNode node2 in nodeList1) //當(dāng)然也能用nodeList的值
{
if (node2.Attributes["Name"].InnerText == "Person2")
{
Console.WriteLine(node2.ChildNodes[1].InnerText);
}
}
//3.2 讀取ID為2所在的節(jié)點(diǎn)第二個(gè)子節(jié)點(diǎn)Name的InnerText
XmlNode node3 = doc.SelectSingleNode("PersonF/person[ID=2]");
string strNode3 = node3.ChildNodes[1].InnerText;
//3.3利用下面的方法可以找到ID為2的節(jié)點(diǎn)
XmlNodeList nodeList2 = doc.SelectNodes("http://person//ID");
XmlNode node4 = null;
foreach (XmlNode node5 in nodeList2)
{
if (node5.InnerText == "2")
{
node4 = node5;
break;
}
}
Console.WriteLine(node4.InnerText);
//4、讀取節(jié)點(diǎn)的屬性
string Name = node.Attributes["Name"].InnerText;
//5 修改節(jié)點(diǎn)的屬性
node.Attributes["Name"].InnerText = "work hard work smart!";
doc.Save(path);
//6 添加自定義的節(jié)點(diǎn)
XmlTextReader reader = new XmlTextReader(path);
XmlElement root = doc.DocumentElement;//獲取根節(jié)點(diǎn)
XmlElement tagOuter = doc.CreateElement("person");
XmlElement tagIN = doc.CreateElement("Name");
tagIN.InnerText = "work hard work smart!";
tagOuter.AppendChild(tagIN);
root.AppendChild(tagOuter);//添加tagOuter到XML文件的最后
reader.Close();
doc.Save(path);
}
catch (System.Exception e)
{
throw new Exception(e.Message);
}
}

相關(guān)文章

最新評(píng)論