How to append to a Xml file for each operation? - c#

I am developing a tool to reads a XMl(input) which contains paths to some folders and files and generate a XML(output) based on the information of all files mentioned in the path. I tried the a code which reads the input xml file where i have give path to a certain folder within a certain tag. The tool works perfectly if i have mentioned only one path in the input xml. But on adding another path the previous the previous contents written to the XML(output) generated are overwritten.I have given the code below for the button event which generates the output XML on click and method that writes details to the XML. I an not sure how to append or where to append in the method that i write details to xml. Please help me out.
public bool GenerateReportFile(InputFile inputFile, string xmlfile)\\button clicked to perform operation
{
//try
//{
//
foreach (var folder in inputFile.FolderList)
{
List<string> foldersList = GetSubFolders(folder);
foldersList.Add(folder);
UpdateFileInfomation(foldersList);
SetVariable(folder);
Serialize(xmlfile, typeof(DeploymentInfo), filesInformation);
}
private static void Serialize(string xmlFilePath, Type type, object obj)\\method that writes contents to xml
{
if (obj == null)
return;
if (!Directory.Exists(Path.GetDirectoryName(xmlFilePath)))
Directory.CreateDirectory(Path.GetDirectoryName(xmlFilePath));
try
{
XmlSerializer serializer = new XmlSerializer(type);
TextWriter textWriter = new StreamWriter(xmlFilePath);\\this line creates a new XML file every time. this is where i need to handle things to avoid overwriting for every path mentioned in my input xml but i am unable to
serializer.Serialize(textWriter, obj);
textWriter.Close();
}
catch (Exception ex)
{
throw ex;
}
}

If your intention is to serialize objects of the same type at a single location you can add them to a list and serialize it instead.
Here is a tutorial:
http://www.dotnetperls.com/serialize-list
Edit:
This only works for Binary Serialization, not XML
You would need to rework your functions a bit:
Your GenerateReportFile should generate the list of objects and pass it to your Serialize

Related

Passing XML from XSLT to C# function

I got an XSLT variable resultxml which holds a complete xml. Now I want to save this XML in to a xml File.
I had written some code like this
In XSLT
<xsl:value-of select="XSLTHelper:SaveXML($resultxml)"/>
In C#
public static void SaveXML(string xmls)
{
File.WriteAllText( HttpContext.Current.Server.MapPath("~/App_Data/missing_data.xml"), xmls.ToString());
}
Data saves correctly but not in XML format just a string value. Is there is any way that I can maintain my XML structure and save it in File?
Assuming you pass in some nodes from XSLT and not a string you might want to try whether using
public static void SaveXML(XPathNodeIterator nodes)
{
foreach (XPathNavigator node in nodes)
{
using (XmlWriter xw = XmlWriter.Create(HttpContext.Current.Server.MapPath("~/App_Data/missing_data.xml")))
{
node.WriteSubtree(xw);
}
}
}
instead of public static void SaveXML(string xmls) gives you the result you want. Of course the code I posted that writes to a single file is kind of nonsense if you really passed in several nodes to your function, but assuming you pass in a single node it should write that to the file HttpContext.Current.Server.MapPath("~/App_Data/missing_data.xml").

Read XML values Webservice

I want to read xml on runtime, without save it on a path
After my searching i find that, In console application i need to use Console.Out for displaying result
xmlSerializer.Serialize(Console.Out, patient);
In Windows / Web Application we need to set path like
StreamWriter streamWriter = new StreamWriter(#"C:\test.xml");
but i need to read xml with out save it, i am using Webserive where i need to read it and take a decision that either it is valid or not
I hope i define it clearly..
Use the XmlDocument object.
There are several ways to load the XML, you can use the XmlDocument.Load() and specify your URL in there or use XmlDocument.LoadXml() to load the XML from a string.
You could use the XmlDocument.LoadXml class to read the received xml. There is no need to save it to disk.
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(receivedXMLStr);
//valid xml
}
catch (XmlException xe)
{
//invalid xml
}
Use Linq2Xml..
XElement doc;
try
{
doc=XElement.Load(yourStream);
}
catch
{
//invalid XML
}
foreach(XElement node in doc.Descendants())
{
node.Value;//value of this node
nodes.Attributes();//all the attributes of this node
}
Thanks all of you for your reply, i want to laod my XML without save it on a local Path, because saving creating many XML.
Finally i find the solutions for load the XML from class on a Memory stream, I thinn this solution is very easy and optimize
XmlDocument doc = new XmlDocument();
System.Xml.Serialization.XmlSerializer serializer2 = new System.Xml.Serialization.XmlSerializer(Patients.GetType());
System.IO.MemoryStream stream = new System.IO.MemoryStream();
serializer2.Serialize(stream, Patients);
stream.Position = 0;
doc.Load(stream);
You need to use the Deserialize option to read the xml. Follow the below steps to achieve it,
Create a target class. It structure should represent the xml output.
After creating the class, use the below code to load your xml into the target object
TargetType result = null;
XmlSerializer worker = new XmlSerializer(typeof(TargetType));
result = worker.Deserialize("<xml>.....</xml>");
Now the xml is loaded into the object 'result' and use it.

XmlDocument in WCF Service method not successfully saving to file using the class' save method

Hello and thanks in advance,
I am attempting to take the input from text boxes in a silverlight application and on an event fired by a button click, convert them to an xml string, pass the string and a specified file name to a WCF service call and in that call save the xml to the specifed file(via a string parameter). The code which captures the text into an xml string seems to be successfully working(based on what I see in the variables when debugging) and looks like this:
private void ServerInfoNext_Click(object sender, RoutedEventArgs e)
{
//new RegisterServerGroupObject instance
RegisterServerGroupObject groupInfo= new RegisterServerGroupObject(groupNameTB.Text,1,parentServerNameTB.Text,LeaderNameCB.SelectedItem.ToString());
var serializer = new XmlSerializer(typeof(RegisterServerGroupObject));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("","");
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.Indent = true;
settings.CloseOutput = true;
StringBuilder sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb,settings))
{
serializer.Serialize(writer, groupInfo);
writer.Close();
}
//sb now contains the xml string with the information from the serialized class
string contentsString = sb.ToString();
//create instance of XmlWrite service
XMLWriteServiceClient xmlClient = new XMLWriteServiceClient();
xmlClient.WriteXmlToServerCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(xmlClient_WriteXmlToServerCompleted);
xmlClient.WriteXmlToServerAsync("ServerGroups.xml", contentsString);
}
at this point when the variable contents string is passed to the service method, I can see that it has valid xml, as well as within the service method itself, which looks like this:
public class XMLWriteService : IXMLWriteService
{
public void WriteXmlToServer(string filename,string xmlString)
{
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(xmlString.ToString());
try
{
xDoc.Save(filename);
}
catch (FileNotFoundException e)
{
Console.WriteLine(e.InnerException.ToString());
}
}
}
The try/catch block is not indicating that the file("ServerGroups.xml") is not found, and I currently have that xml file in the ClientBin of the server side portion of the project. (the .Web side). However, after the method terminates there is no new xml written to the file. Can someone please tell me what I am doing wrong? I don't know why the XmlDocument class instance is not saving its contents to the file. Thanks in advance!
You aren't passing a path, so it's just going to save the file to the current directory of the WCF service process, whatever that happens to be. Either find out what that is, or do a search on your whole server drive for that file name to see where it's saving it. Better yet, call Path.Combine to append a path to the begining of the file name before you save to it. For instance:
xDoc.Save(Path.Combine("C:\\ClientBin", filename));
To answer your question in the comment below, if you want to append the incoming XML data to the data that is already stored in the XML file on the server, that's a bit more involved. It all depends what the format of the XML is. Since you are using serialization, which by default will only allow one object per XML document (because it puts the object name as the root document element, of which there can only be one), then you would have to have a different XML format. For instance, on the server side, you would need to have some kind of root element on the document under which you could keep appending the incoming RegisterServerGroupObject objects. For instance, if your XML file on the server looked like this:
<?xml version="1.0" encoding="utf-8" ?>
<ListOfRegisterServerGroupObject>
</ListOfRegisterServerGroupObject>
Then, you could append the data by inserting new elements within that root element, like this:
<?xml version="1.0" encoding="utf-8" ?>
<ListOfRegisterServerGroupObject>
<RegisterServerGroupObject>
...
</RegisterServerGroupObject>
<RegisterServerGroupObject>
...
</RegisterServerGroupObject>
...
</ListOfRegisterServerGroupObject>
To do this, you would need to first load the XML document, then get the root element, then append the incoming XML as a child element. For instance:
public void WriteXmlToServer(string filename, string xmlString)
{
string filePath = Path.Combine("C:\\ClientBin", filename);
XmlDocument storage = New XmlDocument();
storage.Load(filePath);
XmlDocument incoming = New XmlDocument();
incoming.LoadXml(xmlString);
storage.DocumentElement.AppendChild(incoming.DocumentElement);
storage.Save(filePath);
}
You may need to 'map' the physical path to the output file within the service
string path = HostingEnvironment.MapPath("~/MyPath/MyFile.xml");

serialize to XML path issue

I am trying to serialize my Report class info to an XML. At this point I think all of the serialize and deserialize code works, but for the initial write, I'm having trouble performing the serialize, because the XML file doesn't exist yet.
for an empty text file, i can use:
StreamWriter sw = File.CreateText(#"path");
sw.Close();
this is my code block for the serializing. the exception (Directory not found) is getting thrown on the StreamWriter line. I'd like to simply add an if(!File.Exists(xmlPath))...create empty XML. Or maybe there is a more correct way to do this.
public void SerializeToXML(Report newReport)
{
XmlSerializer serializer = new XmlSerializer(typeof(Report));
TextWriter textWriter = new StreamWriter(xmlPath);
serializer.Serialize(textWriter, newReport);
textWriter.Close();
}
The StreamWriter(String) constructor will create the file if it does not already exist:
If the file exists, it is overwritten; otherwise, a new file is created.
However, it will not create any inexistent directories in your path.
DirectoryNotFoundException: The specified path is invalid, such as being on an unmapped drive.
To create any required directories, you can include the following code (at the beginning of your SerializeToXML method):
var dir = Path.GetDirectoryName(xmlPath);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
First to make sure the directory exist you can use:
Directory.CreateDirectory(#"c:\directory\subdirectory");
You don't have to check if directory already exist.
A easy way to convert public classes to XML is to use the following snippet:
public static string ToXml<T>(T obj)
{
using (var ms = new MemoryStream())
using (var sr = new StreamReader(ms))
{
var xmlSer = new XmlSerializer(typeof(T));
xmlSer.Serialize(ms, obj);
ms.Seek(0, SeekOrigin.Begin);
return sr.ReadToEnd();
}
}
Then you could just use the following code to write it to a file:
var xmlString = Util.ToXml(report);
File.WriteAllText(#"path", xmlString);
(this example is without error handling)
Also, in your code you forgot to close/dispose the TextWriter. I would recommend using the using-statement to handle it for you.
CreateText, and the StreamWriter, will create files if they don't exist, but they won't create directories that don't already exist for you. Is your path correct?
Try Checking with a Directory.Exists(Path.GetDirectoryName(xmlPath)).

How to Update a XML Node?

It is easy to read an XML file and get the exact Node Text, but how do I Update that Node with a new value?
To read:
public static String GetSettings(SettingsType type, SectionType section)
{
XmlTextReader reader = new XmlTextReader(HttpContext.Current.Request.MapPath(APPSETTINGSPATH));
XmlDocument document = new XmlDocument();
document.Load(reader);
XmlNode node = document.SelectSingleNode(
String.Format("/MyRootName/MySubNode/{0}/{1}",
Enum.Parse(typeof(SettingsType), type.ToString()),
Enum.Parse(typeof(SectionType), section.ToString())));
return node.InnerText;
}
to write ...?
public static void SetSettings(SettingsType type, SectionType section, String value)
{
try
{
XmlTextReader reader = new XmlTextReader(HttpContext.Current.Request.MapPath(APPSETTINGSPATH));
XmlDocument document = new XmlDocument();
document.Load(reader);
XmlNode node = document.SelectSingleNode(
String.Format("/MyRootName/MySubNode/{0}/{1}",
Enum.Parse(typeof(SettingsType), type.ToString()),
Enum.Parse(typeof(SectionType), section.ToString())));
node.InnerText = value;
node.Update();
}
catch (Exception ex)
{
throw new Exception("Error:", ex);
}
}
Note the line, node.Update(); does not exist, but that's what I wanted :)
I saw the XmlTextWriter object, but it will write the entire XML to a new file, and I just need to update one value in the original Node, I can save as a new file and then rename the new file into the original name but... it has to be simpler to do this right?
Any of you guys have a sample code on about to do this?
Thank you
You don't need an "update" method - setting the InnerText property updates it. However, it only applies the update in memory. You do need to rewrite the whole file though - you can't just update a small part of it (at least, not without a lot of work and no out-of-the-box support).
XmlDocument.Load has an overload that will take the filename directly so there is no need for the reader.
Similarly when you are done XmlDocument.Save will take a filename to which it will save the document.
The nodeValue property can be used to change the value of a text node.
The following code changes the text node value of the first element:
Example:
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Cooking";
source: http://www.w3schools.com/DOM/dom_nodes_set.asp
You're updating the node in an in-memory representation of the xml document, AFAIK there's no way to update the node directly in the physical file. You have to dump it all back to a file.

Categories