[转载]C# 对XML基本操作总结 – work hard work smart – 博客园.
C# 对XML基本操作包括读取节点的数据,添加节点。读取节点属性,修改节点属性等。具体如下:
XML文件:文件在MyDocument文件夹下
<?xml version="1.0" encoding="utf-8"?>
<PersonF xmlns="" Name="(test)work hard work smart!"> |
Code:说明都在注释里。
XmlDocument doc = new XmlDocument(); |
XmlNode node = doc.SelectSingleNode("PersonF"); |
XmlNodeList nodeList1 = doc.SelectNodes("PersonF/person"); |
XmlNodeList nodeList = doc.DocumentElement.GetElementsByTagName("person"); |
foreach (XmlNode node2 in nodeList1) |
if (node2.Attributes["Name"].InnerText == "Person2") |
Console.WriteLine(node2.ChildNodes[1].InnerText); |
XmlNode node3 = doc.SelectSingleNode("PersonF/person[ID=2]"); |
string strNode3 = node3.ChildNodes[1].InnerText; |
XmlNodeList nodeList2 = doc.SelectNodes("//person//ID"); |
foreach (XmlNode node5 in nodeList2) |
if (node5.InnerText == "2") |
Console.WriteLine(node4.InnerText); |
string Name = node.Attributes["Name"].InnerText; |
node.Attributes["Name"].InnerText = "work hard work smart!"; |
XmlTextReader reader = new XmlTextReader(path); |
XmlElement root = doc.DocumentElement; |
XmlElement tagOuter = doc.CreateElement("person"); |
XmlElement tagIN = doc.CreateElement("Name"); |
tagIN.InnerText = "work hard work smart!"; |
tagOuter.AppendChild(tagIN); |
root.AppendChild(tagOuter); |
catch (System.Exception e) |
throw new Exception(e.Message); |
}