Click here to Skip to main content
15,912,507 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi i using this code to write into xml files
C#
XmlTextWriter writer = new XmlTextWriter("test.xml", Encoding.UTF8);

writer.WriteStartDocument();

writer.WriteStartElement("C");

writer.WriteStartElement("Subject");
writer.WriteString(txtSubject.Text);
writer.WriteEndElement();//Subject

foreach (string item in listBox1.Items)
{
    writer.WriteStartElement("Items");
    writer.WriteString(item);
    writer.WriteEndElement();//Items
}
writer.WriteEndElement();//C

writer.WriteEndDocument();

writer.Close();

now i want to add some items to this but its not adding into xml file, its write again of zero
how can i add some more items to my xml file?
With Respect
Posted
Comments
Thomas Daniels 4-Feb-15 12:13pm    
Can you please show the code where you try to add some more items?
Avenger1 4-Feb-15 14:30pm    
i don't know how to add and i have just this code

1 solution

Based on your supplied code:

C#
private void AppendItems()
{
    string subject = "TestSubject";
    List<string> listItems = new List<string>();
    listItems.Add("Items5");
    listItems.Add("Items6");

    XmlDocument xDoc = new XmlDocument();
    xDoc.Load("test.xml");

    XmlNode subjectNode = xDoc.DocumentElement.SelectSingleNode("Subject['" + subject + "']");
    foreach (string item in listItems)
    {
        XmlNode newItem = xDoc.CreateNode(XmlNodeType.Element, "Items", xDoc.NamespaceURI);
        newItem.InnerText = item;
        subjectNode.ParentNode.AppendChild(newItem);
    }

    xDoc.Save("test.xml");
}
 
Share this answer
 
v2
Comments
Avenger1 4-Feb-15 23:30pm    
thanks this code answered
can you write to me about Update and search, please?
With Respect
Gideon van Dyk 5-Feb-15 16:18pm    
SelectSingleNode and SelectNodes are your best bet at finding nodes based on XPath.

My example basically selected the Subject Element with the inner text of what's supplied. You can update anything on the node returned by first casting it to an XmlElement and then you can add, modify, remove attributes, child nodes and values.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900