What I’m trying to do here is see whether the element exists in the xml document, if it does exist then i want to modify the inner text of it. if it doesnt exist i would like to create it and also create the appropriate inner text for it. However, when it an element does exist and i try to change it’s inner text to something shorter than it was the whole xml files writing seems to shift.
My code:
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(path);
XmlNodeList felement = xmldoc.GetElementsByTagName(Element);
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
if (felement.Count == 0)
{
XmlElement elmRoot = xmldoc.DocumentElement;
XmlElement xmlele = xmldoc.CreateElement(Element);
xmlele.AppendChild(xmldoc.CreateTextNode(data));
elmRoot.AppendChild(xmlele);
xmldoc.Save(fs);
}
else
{
felement[0].InnerText = data;
xmldoc.Save(fs);
}
fs.Close();
XML File before modifying with a shorter inner text:
<?xml version="1.0" encoding="utf-8"?>
<MyXMLFile>
<Source>C:\Users\Dacto\Desktop\</Source>
<Destination>C:\Program Files\Adobe</Destination>
</MyXMLFile>
After shorter inner text:
<?xml version="1.0" encoding="utf-8"?>
<MyXMLFile>
<Source>C:\Users\Dacto\Desktop\Napster</Source>
<Destination>C:\Users</Destination>
</MyXMLFile>/MyXMLFile>
See the “extra” /MyXMLFile> what’s going on??
Since the output isn’t valid XML then it’s unlikely that XmlDocument.Save produced the entire content of the file. Given this, I’d suspect that when creating the FileStream you should supply a different parameter rather than FileMode.Open – FileMode.Create will ensure that the file is truncated before being written to – currently it’s being overwritten, leaving the old content in place if the new file isn’t large enough to cover it.