How To append in the XMl file using XMLWriter class - c#

How To append in the XMl file using XMLWriter class
XmlWriterSettings xmlFragments = new XmlWriterSettings();
xmlFragments.Indent = true ;
XmlTextWriter xWriter = new XmlTextWriter(_logFilePath, null);
xWriter.WriteStartDocument();//starting document
xWriter.WriteStartElement("values");//starting parent node
xWriter.WriteStartElement("values1");//1st child node
xWriter.WriteAttributeString("id", "200");//attributes of child node
xWriter.WriteAttributeString("name", "ABCD");
xWriter.WriteString("ISO Company");//innertext
xWriter.WriteEndElement();
xWriter.WriteStartElement("num");//2nd child node
xWriter.WriteAttributeString("more", "500");
xWriter.WriteAttributeString("less", "101");
xWriter.WriteString("numeric");
xWriter.WriteEndElement();
xWriter.WriteStartElement("r", "runnnig", "");//3rd child node
xWriter.WriteAttributeString("fast", "500km");
xWriter.WriteAttributeString("slow", "10km");
xWriter.WriteString("killometers");
xWriter.WriteEndElement();
xWriter.WriteStartElement("character");
xWriter.WriteAttributeString("char", "a");
xWriter.WriteAttributeString("another", "b");
xWriter.WriteEndElement();
xWriter.WriteEndElement();
xWriter.WriteEndDocument();
xWriter.Close();
I am trying to load xml file in xmlwriter but this class overwrite the previous tag but i dont want to overwrite the tag.

It can be solved by XmlDocument.
XmlDocument doc = new XmlDocument();
doc.Load("test.xml");
XmlElement el = doc.CreateElement("child");
el.InnerText = "This row is being appended to the end of the document.";
doc.DocumentElement.AppendChild(el);
doc.Save("test.xml");
check here for more options.

Related

trying to save xml file in unity c# but getting an empty file

I am tying to save an xml file but the file I get is completely empty, not even the tags.
Even simple files are not being saved correctly, for example:
XmlDocument xmlDoc = new XmlDocument();
XmlElement root = xmlDoc.CreateElement("root");
XmlElement element = xmlDoc.CreateElement("element");
root.AppendChild(element); // add element to root
XmlElement Name = xmlDoc.CreateElement("Name");
Name.InnerText = "NameElement";
element.AppendChild(Name); // add Name to element
xmlDoc.AppendChild(root); // add root to document
xmlDoc.Save(path);
if (File.Exists(path))
Debug.Log("xml saved");
I am getting the "xml saved" message in the log but the file that is being created is completely empty.
Its ease. You must to append element to root at the end of method. Firstly insert need data in element. In the end append element to root.
XmlDocument xmlDoc = new XmlDocument();
XmlElement root = xmlDoc.CreateElement("root");
XmlElement element = xmlDoc.CreateElement("element");
XmlElement Name = new XmlElement("name string")
element.Add(Name); // add Name to element
root.AppendChild(element); // add element to root
xmlDoc.AppendChild(root); // add root to document
xmlDoc.Save(path);
if (File.Exists(path))
Debug.Log("xml saved");

Token StartElement in state Epilog would result in an invalid XML document

I am getting the error "Token StartElement in state Epilog would result in an invalid XML document." when i get the data from datatable and try to convery it to xml file .
Code :
DataTable dtTest = new DataTable();
dtTest.Columns.Add("Name");
dtTest.Columns.Add("NickName");
dtTest.Columns.Add("Code");
dtTest.Columns.Add("reference");
dtTest.Rows.Add("Yash", "POPs", "Vapi", "None1");
dtTest.Rows.Add("shilpa", "shilpa", "valsad", "None2");
dtTest.Rows.Add("Dinesh", "dinu", "pune", "None3");
dtTest.Rows.Add("rahul", "mady", "pardi", "None4");
XmlWriterSettings settings = new XmlWriterSettings();
StringWriter stringwriter = new StringWriter();
XmlTextWriter xmlTextWriter = new XmlTextWriter(stringwriter);
xmlTextWriter.Formatting = Formatting.Indented;
xmlTextWriter.WriteStartDocument();
foreach (var row in dtTest.AsEnumerable())
{
xmlTextWriter.WriteStartElement("");
xmlTextWriter.WriteAttributeString("orderid", row.Field<string>("Name"));
xmlTextWriter.WriteElementString("type", row.Field<string>("Name"));
xmlTextWriter.WriteElementString("status", row.Field<string>("Name"));
xmlTextWriter.WriteElementString("productno", row.Field<string>("Name"));
xmlTextWriter.WriteEndElement();
}
XmlDocument docSave = new XmlDocument();
docSave.LoadXml(stringwriter.ToString());
What is the cause of this error, and how can it be fixed?
You have a few problems here:
You are writing multiple root elements to your document, one for each call to xmlTextWriter.WriteStartElement(""). However, a well-formed XML document must have one and only one root element, so you need to wrap your row elements in some container element.
(You might have been thinking that WriteStartDocument() would write the root element, but it does not. It just writes the XML declaration.)
You are using XmlTextWriter but this class is deprecated. From the docs:
Starting with the .NET Framework 2.0, we recommend that you create XmlWriter instances by using the XmlWriter.Create method and the XmlWriterSettings class to take advantage of new functionality.
If you switch to XmlWriter you will get clearer error messages and better error checking.
You are trying to write elements with no name:
xmlTextWriter.WriteStartElement("");
This would result in malformed XML. XmlTextWriter seems not to check for this, but XmlWriter does.
Putting all of the above together, your code can be modified as follows:
var stringwriter = new StringWriter();
using (var xmlWriter = XmlWriter.Create(stringwriter, new XmlWriterSettings { Indent = true }))
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("Root");
foreach (var row in dtTest.AsEnumerable())
{
xmlWriter.WriteStartElement("Row");
xmlWriter.WriteAttributeString("orderid", row.Field<string>("Name"));
xmlWriter.WriteElementString("type", row.Field<string>("Name"));
xmlWriter.WriteElementString("status", row.Field<string>("Name"));
xmlWriter.WriteElementString("productno", row.Field<string>("Name"));
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
var xml = stringwriter.ToString();
Demo fiddle here.

Why is my XmlDocument.Save() failing with "Resource in use by another process"?

So I need to open an XML document, write to it and then save the file back to disk. Do I need to load the XmlDocument using a filestream to ensure that the stream is closed before saving?
string xmlPath = Server.MapPath("../statedata.xml");
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(xmlPath);
XmlNode node = xmlDocument.SelectSingleNode("//root/state");
node.InnerText = string.Format("org.myorg.application.init = {0};",stateJson);
xmlDocument.Save(xmlPath); //blows up!
I've run into this before. Instead of passing the path directly to Load, create an XmlReader that you can dispose of after the load:
string xmlPath = Server.MapPath("../statedata.xml");
XmlDocument xmlDocument = new XmlDocument();
using(XmlReader reader = XmlReader.Create(xmlPath))
xmlDocument.Load(reader);
XmlNode node = xmlDocument.SelectSingleNode("//root/state");
node.InnerText = string.Format("org.myorg.application.init = {0};",stateJson);
xmlDocument.Save(xmlPath); //blows up!

.net: XmlDocument creates one line xml document

I have a standard XML document, which looks like a 'tree'. I add some nodes and save changes:
XmlDocument doc = new XmlDocument();
doc.Load(filename);
...
doc.PreserveWhitespace = true;
XmlTextWriter writer = new XmlTextWriter(filename, Encoding.Default);
doc.WriteTo(writer);
writer.Close();
and after that xml document stretch into one line. How to add line feeds?
After you construct the XmlTextWriter, but before you call doc.WriteTo(writer);, insert this line:
writer.Formatting = Formatting.Indented;

XDocument.Save() without header

I am editing csproj files with Linq-to-XML and need to save the XML without the <?XML?> header.
As XDocument.Save() is missing the necessary option, what's the best way to do this?
You can do this with XmlWriterSettings, and saving the document to an XmlWriter:
XDocument doc = new XDocument(new XElement("foo",
new XAttribute("hello","world")));
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
StringWriter sw = new StringWriter();
using (XmlWriter xw = XmlWriter.Create(sw, settings))
// or to write to a file...
//using (XmlWriter xw = XmlWriter.Create(filePath, settings))
{
doc.Save(xw);
}
string s = sw.ToString();
A simpler solution than the accepted answer is to use XDocument.ToString() to get the XML text without the header.
Example:
// Load the file
XDocument xDocument = XDocument.Load(fileName);
// Edit the XML...
// Save the edited XML text to file
File.WriteAllText(fileName, xDocument.ToString());

Categories

Resources