Thứ Năm, 28 tháng 2, 2008

Insert new node to file xml

public bool AddAdditionalElementString(string file,string key, string value)
{
try
{
//create our new XmlDocument object
XmlDocument xmlDoc = new XmlDocument();
//load the file
xmlDoc.Load(file);
//use a "query" to get to the main nodes (in this case
//its the "Users" nodes
string query = "/Users/User";
//select the node in the query
XmlNode xmlNode = xmlDoc.SelectSingleNode(query);
//now we create a new element to be added
XmlElement xmlSubCat = xmlDoc.CreateElement(key);
//add the value to the Node
xmlSubCat.InnerText = value;
XmlNode commonParent = xmlNode.ParentNode;
//insert at the end of the toher elements
commonParent.InsertAfter(xmlSubCat, xmlNode);
//save the file
xmlDoc.Save(file);
}
catch (XmlException xml)
{
_returnMessage = xml.Message;
_success = false;
}
catch (Exception ex)
{
_returnMessage = ex.Message;
_success = false;
}
return _success;
}

Không có nhận xét nào: