Xml Document Save call doesn't expire cache dependency - c#

I am working with some codes where I am trying to modify an XML file by loading in XmlDocument and then adding/removing an element. This file has a cache dependency set which triggers a piece of code when ever we change the file. If I edit the file in editor or use FileStream it does expire the cache and trigger codes but not with XmlDocument.Save method. Any idea what could be the reason behind this?
string filePath = Server.MapPath("~/App_Data/ssl.xml");
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlElement ele = doc.CreateElement("directory");
XmlAttribute atr = doc.CreateAttribute("path");
atr.Value = "/";
XmlNode node = doc.DocumentElement.SelectSingleNode("//SecurePages");
node.AppendChild(ele);
doc.Save(filePath);
Above code does modify the file but it doesn't expire the cache item which it should since file is modified. The cache does expire if change the file manually or using FileStream.
UPDATE
I found a workaround which is if I load the XmlDocument using LoadXml method then Save call does trigger the cache dependency. I am still not sure why Load/Save combination doesn't work
string filePath = Server.MapPath("~/App_Data/ssl.xml");
XmlDocument doc = new XmlDocument();
doc.LoadXml(ReadTextFile(filePath));
XmlElement ele = doc.CreateElement("directory");
XmlAttribute atr = doc.CreateAttribute("path");
atr.Value = "/";
XmlNode node = doc.DocumentElement.SelectSingleNode("//SecurePages");
node.AppendChild(ele);
doc.Save(filePath);

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");

How to copy node with all its children from an XML document to another one?

I have some C# code to open an XML document and to append the XML element to the selected node. However, I need to get copy of a bunch of nodes from one XML document to include them in another XML document.
How can I do this?
my C# code
XmlDocument Formal_TemplateField = new XmlDocument();
XmlDocument BuildMyGridView = new XmlDocument();
Formal_TemplateField.Load(Server.MapPath("~/Formal_TemplateField.xml"));
BuildMyGridView.Load(Server.MapPath("~/BuildMyGridView.xml"));
XmlElement controls = (XmlElement)Formal_TemplateField.SelectSingleNode("controls");
XmlElement Columns = BuildMyGridView.GetElementById("Columns");
Columns.AppendChild(controls); //<--- error here
BuildMyGridView.Save(Server.MapPath("~/BuildMyGridView.xml"));
This code gives me an error (System.NullReferenceException: 'Object reference not set to an instance of an object.')!
What is wrong?
I found the solution and the code will be just like this.
C#
XmlDocument Formal_TemplateField = new XmlDocument();
XmlDocument BuildMyGridView = new XmlDocument();
Formal_TemplateField.Load(Server.MapPath("~/Formal_TemplateField.xml"));
BuildMyGridView.Load(Server.MapPath("~/BuildMyGridView.xml"));
XmlNode NEW_NOOD = BuildMyGridView.ImportNode(Formal_TemplateField.DocumentElement["controls"], true);
BuildMyGridView.DocumentElement.GetElementsByTagName("Columns")[0].AppendChild(NEW_NOOD);
BuildMyGridView.Save(Server.MapPath("~/BuildMyGridView.xml"));

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!

Trying to parse xml, but xmldocument.loadxml() is trying to download?

I have a string input that i do not know whether or not is valid xml.
I think the simplest aprroach is to wrap
new XmlDocument().LoadXml(strINPUT);
In a try/catch.
The problem im facing is, sometimes strINPUT is an html file, if the header of this file contains
<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">
<html xml:lang=""en-GB"" xmlns=""http://www.w3.org/1999/xhtml"" lang=""en-GB"">
...like many do, it actually tries to make a connection to the w3.org url, which i really dont want it doing.
Anyone know if its possible to just parse the string without trying to be clever and checking external urls? Failing that is there an alternative to xmldocument?
Try the following:
XmlDocument doc = new XmlDocument();
using (var reader = XmlReader.Create(new StringReader(xml), new XmlReaderSettings() {
ProhibitDtd = true,
ValidationType = ValidationType.None
})) {
doc.Load(reader);
}
The code creates a reader that turns off DTD processing and validation. Checking for wellformedness will still apply.
Alternatively you can use XDocument.Parse if you can switch to using XDocument instead of XmlDocument.
I am not sure about the reason behind the problem but Have you tried XDocument and XElement classes in System.Xml.Linq
XDocument document = XDocument.Load(strINPUT , LoadOptions.None);
XElement element = XElement.Load(strINPUT );
EDIT: for xml as string try following
XDocument document = XDocument.Parse(strINPUT , LoadOptions.None );
Use XmlDocument's load method to load the xml document, use XmlNodeList to get at the elements, then retrieve the data ...
try the following:
XmlDocument xmlDoc = new XmlDocument();
//use the load method to load the XML document from the specified stream.
xmlDoc.Load("myXMLDoc.xml");
//Use the method GetElementsByTagName() to get elements that match the specified name.
XmlNodeList item = xDoc.GetElementsByTagName("item");
XmlNodeList url = xDoc.GetElementsByTagName("url");
Console.WriteLine("The item is: " + item[0].InnerText));
add a try/catch block around the above code and see what you catch, modify your code to address that situation.

Recreate the same XML document if the original XML document is deleted

I developed a sample application to create an XML document, and I created and saved the XML documented. The application is still running but I delete that XML document and I am now trying to create a new XML using the same application. I got an error of
this document already has 'DocumentElement' node
if (File.Exists(AppPath) == false)
{
root = doc.CreateElement("LicenseDetails");
rootnode = doc.CreateElement("License");
Login = doc.CreateElement("Login_Name");
Login.InnerText = "KSC";
rootnode.AppendChild(Login);
root.AppendChild(rootnode);
doc.AppendChild(root);
doc.Save(AppPath);
}
I can easily append the node in existing XML document but what I want to do is: if my XML got deleted, application has to create a new XML with same tags.
The issue is even if you delete the XML, the doc element you are using is the same one as before. So when you try to add the root element to the doc element exception is thrown. A possible solution is as as follows:
eg:
XmlDocument doc;
XmlElement root;
XmlElement rootnode;
XmlElement Login;
if (File.Exists(#"C:\Test.xml") == false)
{
doc = new XmlDocument();
root = doc.CreateElement("LicenseDetails");
rootnode = doc.CreateElement("License");
Login = doc.CreateElement("Login_Name");
Login.InnerText = "KSC";
rootnode.AppendChild(Login);
root.AppendChild(rootnode);
doc.AppendChild(root);
doc.Save(#"C:\Test.xml");
}
So when you get to this block again it will execute without issues.
Use DocumentElement property - It return the root element of Xml document.
XmlDocument dom=new XmlDocument();
dom.Load("file.xml");
XmlElement ele1=dom.createElement("A");
XmlElement ele2=dom.createElement("B");
ele1.AppendChild(ele2);
dom.DocumentElement.AppendChild(ele1);
dom.Save("file.xml");

Categories

Resources