C# XML Serilization & Appending new data - c#

I am trying to create an XML file with the following structure
However, this is what I get (one line):
<?xml version="1.0" encoding="utf-8"?><!--This file is generated by the program.--><root><OFBM time="9:15" date="22.06.2016"><folder>file:///C:/Program Files (x86)/Cisco/Cisco AnyConnect Secure Mobility Client</folder><folder>file:///C:/Arduino223</folder></OFBM></root>
My code:
public void CreateXML()
{
XmlWriter writer = XmlWriter.Create(#"C:\Users\Alek\Dropbox\D\Debug\product.xml");
writer.WriteStartDocument();
writer.WriteComment("This file is generated by the program.");
writer.WriteStartElement("root");
writer.WriteStartElement("OFBM");
writer.WriteAttributeString("time", "9:15");
writer.WriteAttributeString("date", "22.06.2016");
writer.WriteElementString("folder", #"file:///C:/Program Files (x86)/Cisco/Cisco AnyConnect Secure Mobility Client");
writer.WriteElementString("folder", #"file:///C:/Arduino223");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
writer.Close();
}
How do I also append new data? Instead of creating a new XML each time.

Add some settings to achieve the indent you are trying to accomplish in your XML file:
//I added this part (XmlWriterSettings):
XmlWriterSettings mySettings = new XmlWriterSettings();
mySettings.Indent = true;
mySettings.IndentChars = (" ");
mySettings.CloseOutput = true;
mySettings.OmitXmlDeclaration = true;
//Added the settings you intialize and set on your XmlWriter:
XmlWriter writer = XmlWriter.Create(#"C:\Users\Alek\Dropbox\D\Debug\product.xml", mySettings);
writer.WriteStartDocument();
writer.WriteComment("This file is generated by the program.");
writer.WriteStartElement("root");
writer.WriteStartElement("OFBM");
writer.WriteAttributeString("time", "9:15");
writer.WriteAttributeString("date", "22.06.2016");
writer.WriteElementString("folder", #"file:///C:/Program Files (x86)/Cisco/Cisco AnyConnect Secure Mobility Client");
writer.WriteElementString("folder", #"file:///C:/Arduino223");
writer.WriteEndElement();
//writer.WriteEndElement();
//writer.WriteEndDocument();
writer.Flush();
writer.Close();
To append new data without recreating the file, you can do this:
XDocument doc = XDocument.Load(#"C:\Users\Alek\Dropbox\D\Debug\product.xml");
XElement school = doc.Element("root");
school.Add(new XElement("OFBM",
new XElement("folder", "file:///C:/Arduino223")));
doc.Save(#"C:\Users\Alek\Dropbox\D\Debug\product.xml");

Related

Not Writing data to xml file as expected

there are some records in the recordlist but when I am calling the following method, it is not writing the data to xml. it is just writing .
I am absolutely new to XML. Please help me.
public void SaveRentalRecords()
{
// create the XmlWriterSettings object
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = (" ");
// create the XmlWriter object
XmlWriter xmlOut = XmlWriter.Create(path, settings);
// write the start of the document
xmlOut.WriteStartDocument();
xmlOut.WriteStartElement("RentalRecords");
// write each Product object to the xml file
foreach (RecordList record in Records)
{
xmlOut.WriteStartElement("RentalRecord");
xmlOut.WriteElementString("TenantID", record.TenantID);
xmlOut.WriteElementString("TenantName", record.TenantName);
xmlOut.WriteElementString("PropertyID", record.PropertyID);
xmlOut.WriteElementString("PropertyAddress", record.PropertyAddress);
xmlOut.WriteEndElement();
MessageBox.Show(record.TenantID+record.TenantName+record.PropertyID+record.PropertyAddress);
}
// write the end tag for the root element
xmlOut.WriteEndElement();
// close the XmlWriter object
xmlOut.Close();
}
You can try the below approach :
var result = new XElement("RentalRecords", new XElement("RentalRecord", recs.Select(x => new XElement(x.tenantId.ToString(CultureInfo.InvariantCulture), x.tenantName, x.PropertyId.ToString(CultureInfo.InvariantCulture), x.PropertyName))));
result.Save("RentalRecords.xml");

Append to an XML File using XMLWriter class in C#

I have a method which creates an xml file and this method is frequently called from other classes. I have sent three parameters to this method and while writing the xml file I need to append in the xml file with those three parameters. Here's my code snippet
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create(#"E:\\log.xml", settings);
writer.WriteStartDocument();
writer.WriteStartElement("Log");
writer.WriteStartElement("Tests");
writer.WriteStartElement("Test");
writer.WriteAttributeString("Test", message);
writer.WriteElementString("DateAndTime", time);
writer.WriteElementString("Result", test);
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
writer.Close();
I get his output :
<?xml version="1.0" encoding="utf-8"?>
<Log>
<Tests>
<Test Test="LoginToAcrm">
<DateAndTime>2014-20-28 06:20:40</DateAndTime>
<Result>Passed</Result>
</Test>
</Tests>
</Log>
Can anyone please tell me what should I change in my code so that when I call the method again with these three parameters it will append to this xml file with the same format, not overwrite the previous file. Something will be like this:
<?xml version="1.0" encoding="utf-8"?>
<Log>
<Tests>
<Test Test="LoginToAcrm">
<DateAndTime>2014-20-28 06:20:40</DateAndTime>
<Result>Passed</Result>
</Test>
</Tests>
<Tests>
<Test Test="LoginToProjectWithError">
<DateAndTime>2014-09-28 05:10:45</DateAndTime>
<Result>Failed</Result>
</Test>
</Tests>
<Tests>
<Test Test="LoginToProjectWithBlank">
<DateAndTime>2014-09-28 05:12:13</DateAndTime>
<Result>Passed</Result>
</Test>
</Tests>
</Log>
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());
}
You can achieve this by passing List of strings as arguments to the function. And for your help i did the coding of the complete function. Let me know if this work out for you. Check this out
void xmlwriter(List<string> message, List<string> time, List<string> test)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create(#"E:\\log.xml", settings);
writer.WriteStartDocument();
writer.WriteStartElement("Tests");
string[] arrayMessage = message.ToArray();
string[] arrayTime = time.ToArray();
string[] arrayTest = test.ToArray();
for (int i = 0; i < arrayMessage.Length; i++)
{
writer.WriteStartElement("Test");
writer.WriteAttributeString("Test", arrayMessage[i]);
writer.WriteElementString("DateAndTime", arrayTime[i]);
writer.WriteElementString("Result", arrayTest[i]);
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
writer.Close();
}
Note: You may have to add all the values of the parameters to the List before you call the function.
Your desired result isn't a well-formed XML document, since an XML document may only have a single root element.
However, if this is what you want (i.e. rather than an XML document, you want a text document containing XML fragments), you could try the following:
Open the existing file as a FileStream
Seek to the end of file
Pass the FileStream to your XmlWriter constructor
Append the elements you want

Why the WriteElementString() doesn't put a new line in the xml file?

xmlWriter.WriteStartElement("Video");
xmlWriter.WriteElementString("FileName", temp.nameFile);
xmlWriter.WriteElementString("VideoName", temp.nameVideo);
xmlWriter.WriteElementString("Path", temp.path);
xmlWriter.WriteEndElement();
I wrote this part of code with c#, but when I'm going to check the result I see just one row without a new line anywhere!
How is it possible?
Thanks so much!
If you want to have a new line with your xml writer then you should use xml settings like so:
XmlWriterSettings settings = new XmlWriterSettings();
//this will auto indent as well as put everything on a new line
settings.Indent = true;
XmlWriter writer = XmlWriter.Create("file_Name.xml", settings);
writer.WriteStartDocument();
xmlWriter.WriteStartElement("Video");
xmlWriter.WriteElementString("FileName", temp.nameFile);
xmlWriter.WriteElementString("VideoName", temp.nameVideo);
xmlWriter.WriteElementString("Path", temp.path);
xmlWriter.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
writer.Close();
Hope this helps
You may want to pass in settings when constructing your xml writer so it behaves the way you want it to. Check this out for more information.

Formatting XML with tabulation and removing element ending space?

I am trying to do 2 things:
Get the output XML formated with
TABULATION instead of spaces.
Remove the ending space it generates
for video element.
" />
to
"/>
I have tried to use
xmlWriter.Formatting = Formatting.Indented;
as well as
IndentChar
but they did not worked for me dont know why.
This is the code I have currently, I would also like to hear advices and suggestion to improve it:
XmlDocument xmlDoc = new XmlDocument();
XmlTextWriter xmlWriter = new XmlTextWriter(filename, System.Text.Encoding.UTF8);
xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8' standalone='yes'");
xmlWriter.WriteComment(#" This file was made by #author");
xmlWriter.WriteStartElement("videos");
xmlWriter.Close();
xmlDoc.Load(filename);
XmlNode root = xmlDoc.DocumentElement;
foreach (int myID in ExportListIDs)
{
XmlElement video = xmlDoc.CreateElement("video");
root.AppendChild(video);
video.SetAttribute("videoID", myID.ToString());
}
xmlDoc.Save(filename);
I have managed to solve question 1 with the below code but I still don't know if it is possible to remove the space between " and /> at the end of an element vide question 2.
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.Indent = true;
settings.IndentChars = "\t";
XmlWriter writeXML = XmlWriter.Create("test.xml", settings);
writeXML.WriteStartDocument();
writeXML.WriteComment(#" This file was made by #author");
writeXML.WriteStartElement("videos");
foreach (var item in myList)
{
writeXML.WriteStartElement("video");
writeXML.WriteAttributeString("ID", item.Key.ToString());
writeXML.WriteAttributeString("Name", item.Value);
writeXML.WriteStartElement("object");
writeXML.WriteAttributeString("A", item.Key.ToString());
writeXML.WriteAttributeString("B", item.Value);
writeXML.WriteEndElement();
writeXML.WriteEndElement();
}
writeXML.WriteEndElement();
writeXML.WriteEndDocument();
writeXML.Close();

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