How to load multiple files(*.xml) via XmlDocument C# - c#

I wanted to load multiple .xml files in C#. Currently, I am able to load only 1 .xml file.
But not able to find out how will be able to load multiple files .
My code:
XmlDocument doc = new XmlDocument();
string path = #"path of *.xml file"; //
doc.Load(path);

Your code doesn't have to bee too big, you just need to store all the paths in some collection, then you have to apply the same operation to each XML file.
string newValue = "1234";
XmlDocument doc;
var paths = new[] { "config1.xml", "config2.xml" };
paths.ToList().ForEach(path =>
{
doc = new XmlDocument();
doc.Load(path);
// process the document
var nm = new XmlNamespaceManager(doc.NameTable);
var a = doc.SelectSingleNode("//SomeKeyValue", nm);
a.InnerText = newValue;
// save the file
doc.Save(path);
});

Related

Get all the xml childname

I have this code and I found this on internet.
XmlDocument doc = new XmlDocument();
doc.LoadXml("<book ISBN='1-861001-57-5'>" +
"<title>Pride And Prejudice</title>" +
"<price>19.95</price>" +
"</book>");
XmlNode root = doc.FirstChild;
//Display the contents of the child nodes.
if (root.HasChildNodes)
{
for (int i = 0; i < root.ChildNodes.Count; i++)
{
//inner text contains the value of the childnode
Console.WriteLine(root.ChildNodes[i].Name);
}
}
It does work, but when I load the XML file from the disk it doesn't give output. Why?
string xmlText = File.ReadAllText("Filename");
doc.LoadXml(xmlText);
You could use Load method if you have file path.
XmlDocument doc = new XmlDocument();
doc.Load("filepath");
Try this.
XDocument doc = XDocument.Load(Server.MapPath("yourfile.xml"));//Load file from disk
var NodeNames = doc.Descendants("book").Elements().Select(x => x.Name.LocalName).ToList();
You will have to specify the path of folder if your file resides inside folder.

Unable to Load XML file which is dynamically created. And Xml without encoding tag how do i add root encoding tag after creating XML file

if (!File.Exists(locationFile))
{
string file = #"mypathtoxml";
XmlDocument objXmlDoc = new XmlDocument();
doc.Load(file); //- i get error here in loading my XML file which is created dynamically.
//process cannot access my path(my xml file Location) because it is being used by another process
}
You could wait a while and try it again. For example something like this:
var finished = false;
while (!finished)
{
try
{
if (!File.Exists(locationFile))
{
string file = #"mypathtoxml";
XmlDocument objXmlDoc = new XmlDocument();
doc.Load(file);
finished = true;
}
}
catch (IOException)
{
// the file is unavailable because it is:
// - still being written to
// - being processed by another thread
// so we just wait a second
Thread.Sleep(1000);
}
}
In order to terminate sometime, you could add a counter and only try it 10 times or so.
Try this
string file = "<?xml version=\"1.0\"?><mypathtoxml>" + File.ReadAllText(FILENAME) + "</mypathtoxml>";
XmlDocument objXmlDoc = new XmlDocument();
objXmlDoc.LoadXml(file); ​​

Can not read XML document containing ampersand symbol

I am writing a program that reads a XML file with Visual C#. I have a problem reading the Xml file, because it contains invalid XML symbols, for example '&'.
I have to read the XML but I can not modify the document. How can I modify the Xml file using C#? My code so far:
private void button1_Click(object sender, EventArgs e)
{
XmlDocument doc;
doc = new XmlDocument();
doc.Load("nuevo.xml");
XmlNodeList Xpersonas = doc.GetElementsByTagName("personas");
XmlNodeList Xlista = ((XmlElement)Xpersonas[0]).GetElementsByTagName("edad");
foreach (XmlElement nodo in Xlista)
{
string edad = nodo.GetAttribute("edad");
string nombre = nodo.InnerText;
textBox1.Text = nodo.InnerXml;
}
As #EBrown suggested, one possibility would be read the file content in a string variable and replace the & symbol with the correct representation for propert XML & and then parse the XML structure. A possible solution could look like this:
var xmlContent = File.ReadAllText(#"nuevo.xml");
XmlDocument doc;
doc = new XmlDocument();
doc.LoadXml(xmlContent.Replace("&", "&"));
XmlNodeList Xpersonas = doc.GetElementsByTagName("personas");
XmlNodeList Xlista = ((XmlElement)Xpersonas[0]).GetElementsByTagName("edad");
foreach (XmlElement nodo in Xlista)
{
string edad = nodo.GetAttribute("edad");
string nombre = nodo.InnerText;
Console.WriteLine(nodo.InnerXml.Replace("&", "&"));
}
The output is:
34 & 34
If it is ok to use LINQ2XML, then the solution is even shorter, and there is no need to write the reverse(second) replace, because LINQ2XML make this for you automatically:
var xmlContent = File.ReadAllText(#"nuevo.xml");
var xmlDocument = XDocument.Parse(xmlContent.Replace("&", "&"));
var edad = xmlDocument.Root.Element("edad").Value;
Console.WriteLine(edad);
The output is the same as above.

C# crashes on save (doc.Save(PATH);)

This program crashes on debug and highlights the "doc.Save(PATH);" at the end of the code.
I am trying to save the variables cookieScore, additionAddition, and additionMultiplier into an XML file.
I am getting information about it from here "http://visualcsharptutorials.com/net-framework/writing-xml-file"
private XmlDocument doc;
string PATH = #"C:\sample.xml";
private void saveBtn_Click(object sender, EventArgs e)
{
doc = new XmlDocument();
if (!System.IO.File.Exists(PATH))
{
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
XmlComment comment = doc.CreateComment("This is saved game data");
XmlElement root = doc.CreateElement("data");
XmlElement data = doc.CreateElement("data");
XmlAttribute addition = doc.CreateAttribute("addition");
XmlElement additionNumber = doc.CreateElement("additionNumber");
XmlElement multiplicationNumber = doc.CreateElement("multiplicationNumber");
XmlElement cookieSave = doc.CreateElement("cookieSave");
addition.Value = "addition";
additionNumber.InnerText = additionAddition.ToString();
multiplicationNumber.InnerText = additionMultiplier.ToString();
cookieSave.InnerText = cookieScore.ToString();
doc.AppendChild(declaration);
doc.AppendChild(comment);
doc.AppendChild(root);
root.AppendChild(data);
data.Attributes.Append(addition);
data.AppendChild(cookieSave);
data.AppendChild(additionNumber);
data.AppendChild(multiplicationNumber);
doc.Save(PATH);
}
else
{
}
My guess is you're getting an access related exception because you're trying to write to the root of your C drive. Try writing to your desktop instead:
string PATH = #"C:\Users\[yourusername]\Desktop\sample.xml";
Another option would be to try to run your EXE as admin. If it works, then you know that's your problem.

Incorrect parsing of Textbox in docx by OpenXML

I am reading a .docx file using OpenXML in C#. It reads everything correctly but strangely, the content of textbox is being read thrice. What could be wrong? Here is the code to read .docx:
public static string TextFromWord(String file)
{
const string wordmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
StringBuilder textBuilder = new StringBuilder();
using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(file, false))
{
// Manage namespaces to perform XPath queries.
NameTable nt = new NameTable();
XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
nsManager.AddNamespace("w", wordmlNamespace);
// Get the document part from the package.
// Load the XML in the document part into an XmlDocument instance.
XmlDocument xdoc = new XmlDocument(nt);
xdoc.Load(wdDoc.MainDocumentPart.GetStream());
XmlNodeList paragraphNodes = xdoc.SelectNodes("//w:p", nsManager);
foreach (XmlNode paragraphNode in paragraphNodes)
{
XmlNodeList textNodes = paragraphNode.SelectNodes(".//w:t", nsManager);
foreach (System.Xml.XmlNode textNode in textNodes)
{
textBuilder.Append(textNode.InnerText);
}
textBuilder.Append(Environment.NewLine);
}
}
return textBuilder.ToString();
}
The part of file I am talking about is:
The result is: I read it in a test application like this:
What's wrong here?

Categories