C# 读写XML
我们来写;写的方法主要是创建一个XMLDocument,然后可以直接在Document中添加新的Element,也可以使用XPath定位后,结合XmlWriter往Doc里面写,写的方法应该还有很多。但是,够用就好。
代码:
using System.IO;
using System.Xml;
using System.Xml.XPath;
private void button1_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = null;
xmlDoc = new XmlDocument();
string strVersion = "1.0";
string strLevel = "F";
string strFile = "c.cpp";
// Declaration
XmlDeclaration declaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
xmlDoc.AppendChild(declaration);
//--------------------------
// Root element
//--------------------------
XmlElement xmlRoot = xmlDoc.CreateElement("Report");
// Version string
XmlAttribute typeAttribute = xmlDoc.CreateAttribute("Version");
xmlRoot.SetAttributeNode(typeAttribute);
xmlRoot.SetAttribute("Version", strVersion);
// Level string
typeAttribute = xmlDoc.CreateAttribute("Level");
xmlRoot.SetAttributeNode(typeAttribute);
xmlRoot.SetAttribute("Level", strLevel);
// File string
typeAttribute = xmlDoc.CreateAttribute("File");
xmlRoot.SetAttributeNode(typeAttribute);
xmlRoot.SetAttribute("File", strFile);
xmlDoc.AppendChild(xmlRoot);
//--------------------------
// Add Function Element using XmlWriter
//--------------------------
AddFunctionElement(xmlDoc, @"/*", "Main", "1");
// aslo could add statement by using the XPath express "/*/Function[@Name=Main]"
AddStatementElement(xmlDoc, @"/*/Function[@Name='Main']", "If");
xmlDoc.Save(@"d:\test.xml");
}
public void AddFunctionElement(XmlDocument xmlDoc, string strXPath, string strFunctionname, string strNo)
{
XmlElement xmlRoot = xmlDoc.DocumentElement;
// Get the position
XmlNode node = xmlRoot.SelectSingleNode(strXPath);
if (node!=null)
{
XPathNavigator nodesNavigator = node.CreateNavigator();
// Add new Node
XmlWriter summaryWriter = nodesNavigator.AppendChild();
summaryWriter.WriteStartElement("Function");
summaryWriter.WriteStartAttribute("No"); // Attribute "No"
summaryWriter.WriteString(strNo); // Attribute Value
summaryWriter.WriteEndAttribute();
summaryWriter.WriteStartAttribute("Name"); // Attribute "Name"
summaryWriter.WriteString(strFunctionname); // Attribute Value
summaryWriter.WriteEndAttribute();
summaryWriter.WriteEndElement();
summaryWriter.Close();
}
}
public void AddStatementElement(XmlDocument xmlDoc, string strXPath, string strStatement)
{
XmlElement xmlRoot = xmlDoc.DocumentElement;
// Get the position
XmlNode node = xmlRoot.SelectSingleNode(strXPath);
if (node != null)
{
XPathNavigator nodesNavigator = node.CreateNavigator();
// Add new File Node
XmlWriter summaryWriter = nodesNavigator.AppendChild();
summaryWriter.WriteStartElement("Statement");
summaryWriter.WriteStartAttribute("Type"); // Attribute "Type"
summaryWriter.WriteString(strStatement); // Attribute Value
summaryWriter.WriteEndAttribute();
summaryWriter.WriteEndElement();
summaryWriter.Close();
}
}

浙公网安备 33010602011771号