I want to edit my xml file
Hi I am working on XML file, here I want to give rights to user to edit my xml file nodes to his own custom language.
I am enclosing my code, but it is not editting my xml file. Need assistance.
class Program
{
static void Main(string[] args)
{
//The Path to the xml file
string path = "D://Documents and Settings//Umaid//My Documents//Visual Studio 2008//Projects//EditXML//EditXML//testing.xml";
//Create FileStream fs
System.IO.FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//Create new XmlDocument
System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
//Load the contents of the filestream into the XmlDocument (xmldoc)
xmldoc.Load(fs);
//close the fs filestream
fs.Close();
//Change the contents of the attribute
xmldoc.DocumentElement.ChildNodes[0].Attributes[0].InnerText = "Umaid";
// Create the filestream for saving
FileStream WRITER = new FileStream(path, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite);
// Save the xmldocument
xmldoc.Save(WRITER);
//Close the writer filestream
WRITER.Close();
}
}
My XML file which I am going to edit, but couldn't.
<?xml version="1.0" encoding="utf-8" ?>
<rule id="city" scope="public">
<one-of>
<item>Boston</item>
</one-of>
</rule开发者_如何学编程>
What do you really want to do with your XML?? Which attribute to you want to change??
One hint: you can load and save XmlDocument to a path directly - no need for the filestream .....
xmldoc.Load(@"D:\yourpath\file.xml");
xmldoc.Save(@"D:\yourpath\newfile.xml");
The problem is that your expression xmldoc.DocumentElement.ChildNodes[0]
selects the <one-of>
node which has no attributes.
You cannot change a non-existing attribute.
If you want to change the "id" attribute of <rule>
, you need to do this on the DocumentElement:
xmldoc.DocumentElement.Attributes["id"].Value = "Umaid";
If you want to change the text inside the <item>
, do this:
XmlNode itemNode = xmldoc.SelectSingleNode("/rule/one-of/item");
if(itemNode != null)
{
itemNode.InnerText = "Umaid";
}
Marc
class Program
{
static void Main(string[] args)
{
string path = "D:\\Documents and Settings\\Umaid\\My Documents\\Visual Studio 2008\\Projects\\EditXML\\EditXML\\testing.xml";
XmlDocument doc = new XmlDocument();
doc.Load(path);
var itemNode = doc.SelectSingleNode("rule/one-of/item");
if (itemNode != null)
{
itemNode.InnerText = "Umaid";
}
doc.Save(path);
}
}
精彩评论