Appending an Existing Xml File with Xmlwriter

Appending an existing XML file with XmlWriter

finally I succeeded :)

if (!File.Exists("Test.xml"))
{
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Indent = true;
xmlWriterSettings.NewLineOnAttributes = true;
using (XmlWriter xmlWriter = XmlWriter.Create("Test.xml", xmlWriterSettings))
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("School");

xmlWriter.WriteStartElement("Student");
xmlWriter.WriteElementString("FirstName", firstName);
xmlWriter.WriteElementString("LastName", lastName);
xmlWriter.WriteEndElement();

xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Flush();
xmlWriter.Close();
}
}
else
{
XDocument xDocument = XDocument.Load("Test.xml");
XElement root= xDocument.Element("School");
IEnumerable<XElement> rows = root.Descendants("Student");
XElement firstRow= rows.First();
firstRow.AddBeforeSelf(
new XElement("Student",
new XElement("FirstName", firstName),
new XElement("LastName", lastName)));
xDocument.Save("Test.xml");
}

Appending an existing XML file

You should use the XmlDocument class to load the whole file, modify it in memory and then write the contents back replacing the original file. Don't worry, it won't mess up your markup, and you can even ask it to preserve non-significant whitespace in the original document using the PreserveWhitespace property (http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.preservewhitespace.aspx).

C# append node to an existing xml file

I'd suggest to use easier XML API, for example, using XmlDocument :

var doc = new XmlDocument();
doc.Load(conversation_file_name);
var messagesNode = doc.DocumentElement
.SelectSingleNode("/client/conversation/messages");
var lastMessageId = messagesNode.SelectSingleNode("./message[last()]/msg_id");
var id = lastMessageId != null ? int.Parse(lastMessageId.InnerText.Trim()) : 0;

for (int messages_count = 0; messages_count < messages.Count; messages_count++) // Loop through List with for
{
//create nodes to be added to existing XML
var newMessage = doc.CreateElement("message");
var newId = doc.CreateElement("msg_id");
var newRecepient = doc.CreateElement("recepient_id");
var newMessageContent = doc.CreateElement("message");

//set new nodes content
newId.InnerText = messages[messages_count].msg_id.ToString();
newRecepient.InnerText = messages[messages_count].recepient_id.ToString();
newMessageContent.InnerText = messages[messages_count].message.ToString();

//append each node to desired parent node
newMessage.AppendChild(newId);
newMessage.AppendChild(newRecepient);
newMessage.AppendChild(newMessageContent);
messagesNode.AppendChild(newMessage);
}

doc.Save(conversation_file_name);

Append to XML file using XmlWriter

To play with the XML data if you are using .net version 3.5 its better to user LINQ to XML.

http://www.codeproject.com/Articles/24376/LINQ-to-XML

or

Manipulate XML data with XPath and XmlDocument (C#)

OR

Article : How to Append to a Large XML File

I thnik you need to append node to your xmldocuemnt like this

//add to elements collection
doc.DocumentElement.AppendChild(node);

You need to do something like this

XmlDocument xmlDoc=new XmlDocument();

xmlDoc.Load("F:/Documents and Settings/Administrator/Desktop/Account.xml");

XmlElement subRoot=xmlDoc.CreateElement("User");
//UserName
XmlElement appendedElementUsername=xmlDoc.CreateElement("UserName");
XmlText xmlTextUserName=xmlDoc.CreateTextNode(txtUsrName.Text.Trim());
appendedElementUsername.AppendChild(xmlTextUserName);
subRoot.AppendChild(appendedElementUsername);
xmlDoc.DocumentElement.AppendChild(subRoot);
//Email

XmlElement appendedElementEmail=xmlDoc.CreateElement("Email");
XmlText xmlTextEmail=xmlDoc.CreateTextNode(txtEmail.Text.Trim());
appendedElementEmail.AppendChild(xmlTextEmail);
subRoot.AppendChild(appendedElementEmail);
xmlDoc.DocumentElement.AppendChild(subRoot);

xmlDoc.Save("F:/Documents and Settings/Administrator/Desktop/Account.xml");if(!File.Exists("F:/Documents and Settings/Administrator/Desktop/Account.xml"))
{

XmlTextWriter textWritter=new XmlTextWriter("F:/Documents and Settings/Administrator/Desktop/Account.xml", null);
textWritter.WriteStartDocument();
textWritter.WriteStartElement("USERS");
textWritter.WriteEndElement();

textWritter.Close();
}

XmlDocument xmlDoc=new XmlDocument();

xmlDoc.Load("F:/Documents and Settings/Administrator/Desktop/Account.xml");

XmlElement subRoot=xmlDoc.CreateElement("User");
//UserName
XmlElement appendedElementUsername=xmlDoc.CreateElement("UserName");
XmlText xmlTextUserName=xmlDoc.CreateTextNode(txtUsrName.Text.Trim());
appendedElementUsername.AppendChild(xmlTextUserName);
subRoot.AppendChild(appendedElementUsername);
xmlDoc.DocumentElement.AppendChild(subRoot);
//Email

XmlElement appendedElementEmail=xmlDoc.CreateElement("Email");
XmlText xmlTextEmail=xmlDoc.CreateTextNode(txtEmail.Text.Trim());
appendedElementEmail.AppendChild(xmlTextEmail);
subRoot.AppendChild(appendedElementEmail);
xmlDoc.DocumentElement.AppendChild(subRoot);

xmlDoc.Save("F:/Documents and Settings/Administrator/Desktop/Account.xml");

The result'll be like that:

</USERS>
<User>
<UserName>Buggaya</UserName>

<Email>Buggaya@gmail.com</Email>
</User>
</USERS>

orignal post : Append in xml document

XMLWriter formatting when appending to existing XML

FWIW - using the approach suggested by John Saunders and going to XDocument works just fine.

The new content is appended to the existing document with the desired formatting.

How to add data to an existing xml file in c#

Perhaps you should look at some examples using datasets and xml:

http://www.codeproject.com/Articles/13854/Using-XML-as-Database-with-Dataset

or use System.Xml.Serialization.XmlSerializer, when you dont't have amount of records.

Example using XmlDocument

XmlDocument xd = new XmlDocument();
xd.Load("employees.xml");
XmlNode nl = xd.SelectSingleNode("//Employees");
XmlDocument xd2 = new XmlDocument();
xd2.LoadXml("<Employee><ID>20</ID><FirstName>Clair</FirstName><LastName>Doner</LastName><Salary>13000</Salary></Employee>");
XmlNode n = xd.ImportNode(xd2.FirstChild,true);
nl.AppendChild(n);
xd.Save(Console.Out);

Append to an XML File using XMLWriter class in C#

I used some your code, use StringBuilder to create XmlWriter and finally write that string using StreamWriter.

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;

settings.OmitXmlDeclaration = true;
StringBuilder sb = new StringBuilder();

XmlWriter writer = XmlWriter.Create(sb, settings);

writer.WriteStartDocument();

writer.WriteStartElement("Tests");
writer.WriteStartElement("Test");
writer.WriteAttributeString("Test", message);
writer.WriteElementString("DateAndTime", time);
writer.WriteElementString("Result", test);
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
writer.Close();

using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"E:\\log.xml", true))
{
file.Write(sb.ToString());
}

Append XML to file without writing it from scratch?

This totally depends on the position where you need to add the additional elements. Of course you can implement something that removes the closing "</root>" tag, writes additional elements and then adds the "</root>" again. However, such code is highly optimized for your purpose and you'll probably not find a library for it.

Your code could look like this (quick and dirty, without input checking, assuming that <root/> cannot exist):

using System.IO;
using System.Xml.Linq;

namespace XmlAddElementWithoutLoading
{
class Program
{
static void Main()
{
var rootelement = "root";
var doc = GetDocumentWithNewNodes(rootelement);
var newNodes = GetXmlOfNewNodes(doc);

using (var fs = new FileStream("pathToDoc.xml", FileMode.Open, FileAccess.ReadWrite))
{
using (var writer = new StreamWriter(fs))
{
RemoveClosingRootNode(fs, rootelement);
writer.Write(newNodes);
writer.Write("</"+rootelement+">");
}
}
}

private static void RemoveClosingRootNode(FileStream fs, string rootelement)
{
fs.SetLength(fs.Length - ("</" + rootelement + ">").Length);
fs.Seek(0, SeekOrigin.End);
}

private static string GetXmlOfNewNodes(XDocument doc)
{
var reader = doc.Root.CreateReader();
reader.MoveToContent();
return reader.ReadInnerXml();
}

private static XDocument GetDocumentWithNewNodes(string rootelement)
{
var doc = XDocument.Parse("<" + rootelement + "/>");
var childId = "2";
XNamespace ns = "namespace";
doc.Root.Add(new XElement(ns + "anotherChild", new XAttribute("child-id", childId)));
return doc;
}
}
}


Related Topics



Leave a reply



Submit