C# and XML - Read XML files from user-specified location - c#

Read sequentially through the XML files (e.g. C:\Application\XML) and get the xml for all the files.

You can read XML files as shown below:
List<string> files = Directory.GetFiles("c:\\MyDir", "*.xml").ToList();
foreach(string fileLocation in files)
{
XmlDocument obj = new XmlDocument();
obj.Load(filelocation);
//Your code to place the xml in a queue.
}

What you need to do is implement a producer-consumer model. Have a look here: http://www.albahari.com/threading/part4.aspx and scroll down to the "Producer/Consumer Queue" part.
For some classic C# XML API read here: http://msdn.microsoft.com/en-us/magazine/cc302158.aspx

foreach (var file in Directory.EnumerateFiles(path, "*.xml"))
{
var xdoc = XDocument.Load(file);
...
}

Related

Display content dynamic from xml file in zip folder

I´m coding in C# and I have a project that the user will
be able to upload a .zip file and in that file will a .xml be read
and chapters based on xml tags will de displayed dynamic.
Right now it is hardcoded a specific file and in that file
that specific .xml file.
How do I read .xml file from a zip file and display that dynamic in C#?
Microsoft documentation has an exemple on this. Extracting specific file from a zip Archive and unzip them in a directory:
https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-compress-and-extract-files#example-2-extract-specific-file-extensions.
Then you next step will be to process the all or some file from the directory, https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.getfiles?view=netframework-4.7.2#System_IO_Directory_GetFiles_System_String_System_String_
If you don't want to unzip, you can directly open the ZipArchiveEntry, with : https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.ziparchiveentry.open?view=netframework-4.7.2
With multiple Xml files in the zip all serialisation of myTypethe codes should boil down to :
string zipPath = #".\result.zip";
List<myType> listResults ;
using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{
XmlSerializer serializer = new XmlSerializer(typeof(myType);
listResults =
archive
.Entries
.Where(entry => entry.FullName
.EndsWith(".xml", StringComparison.OrdinalIgnoreCase))
.Select(entry => (myType)serializer.Deserialize(entry.Open()))
.ToList();
}
For any missing reference in your project follow the light bulb 💡!
Add the System.IO.Compression.FileSystem assembly to your project references. Once you did that, you can open an archive like this:
static void Main(string[] args)
{
var zipPath = "Path-To-Your-Zipfile";
using (var archive = ZipFile.OpenRead(zipPath))
{
var xmlFile = archive.Entries.FirstOrDefault(e => e.FullName.EndsWith(".xml"));
if(xmlFile == null)
return;
using (var stream = xmlFile.Open())
{
using (var reader = new StreamReader(stream))
{
var fileContents = reader.ReadToEnd();
}
}
}
}

C#. Writing settings to XML file

I have some names of files. I am creating a XML file to store them. When application runs second time it should recognize those file names. Here is my code:
XmlWriter writer = XmlWriter.Create("settings.xml");
writer.WriteStartElement("DialogCreater");
writer.WriteElementString("conditionsFile", conditionsFile);
writer.WriteEndElement();
writer.Close();
But when I use those file names like this:
string[] lines = File.ReadAllLines(charactersFile);
It gives me an error.
System.NotSupportedException
Here how I read them from XML file:
XmlDocument doc = new XmlDocument();
doc.Load("settings.xml");
XmlNodeList node = doc.GetElementsByTagName("files");
foreach (XmlNode n in node[0].ChildNodes)
{
if (n.Name == "conditionsFile") conditionsFile = n.InnerText;
}
NotSupportedException
path is in an invalid format according to msdn documentation. you can fix it by checking path exist or not before reading from itMore info
string path = #"c:\temp\MyTest.txt";
// This text is added only once to the file.
if (!File.Exists(path))
{
//file exist
}

Appending inside a parent tag using XmlWriter

I am using this code to write to a xml document. Issue is every time I call this code it overrides previously written Tags element.
However I want to append multiple Tag elements inside the Tags elements. How can I make such sets using XmlWriter?
using (XmlWriter writer = XmlWriter.Create(path))
{
writer.WriteStartElement("Tags");
writer.WriteElementString("Tag", tagName);
writer.WriteEndElement();
}
I found out over the net few solution involving LINQ, with which I am not very good at. So I am looking something without it?
This can be done via Linq Xml by:
public void AddTagToXml(string path, string tag)
{
XDocument doc;
// Load the existing file
if (File.Exists(path)) doc = XDocument.Load(path);
else
{
// Create a new file with the parent node
doc = new XDocument(new XElement("Tags"));
}
doc.Root.Add(new XElement("tag", tag));
doc.Save(path);
}
It's not terribly efficient as the file is opened and saved on each function call, but it covers your requirements.

Saving Modified XML- WP8 C#

I've been trying to modify and save an xml dynamically. i've tried to find some answers but i didnt manage to.
i Succeeded to modify and change the xml data, but i encounter a problem with saving.
here is the code:
var resourceStreamInfo = Application.GetResourceStream(uri);
using (var stream = resourceStreamInfo.Stream)
{
doc = XDocument.Load(stream);
var Currencies = doc.Descendants("Currency");
XElement root = Currencies.Where(b => b.Element("ID").Value.IndexOf(CurrencyID, StringComparison.CurrentCultureIgnoreCase) >= 0).First();
root.SetElementValue("Rate", rate);
doc.Save(stream);
}
I understood that my stream is readonly, but what should I do?
From Application.GetResourceStreamI guess your are reading a file from your project bundle. You cannot modify it. You need to save the modified file to isolated storage

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.

Categories