C# 我想编辑我的xml文件
您好,我正在处理XML文件,这里我想授予用户将我的XML文件节点编辑为他自己的自定义语言的权限 我附上了我的代码,但它没有编辑我的xml文件。我需要帮助C# 我想编辑我的xml文件,c#,.net,xml,C#,.net,Xml,您好,我正在处理XML文件,这里我想授予用户将我的XML文件节点编辑为他自己的自定义语言的权限 我附上了我的代码,但它没有编辑我的xml文件。我需要帮助 class Program { static void Main(string[] args) { //The Path to the xml file string path = "D://Documents and Settings//Umaid//My Documents//Visua
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();
}
}
我将要编辑但无法编辑的XML文件
<?xml version="1.0" encoding="utf-8" ?>
<rule id="city" scope="public">
<one-of>
<item>Boston</item>
</one-of>
</rule>
波士顿
您真正想用XML做什么??您要更改哪个属性
一个提示:您可以直接加载XmlDocument并将其保存到一个路径中—无需filestream
xmldoc.Load(@"D:\yourpath\file.xml");
xmldoc.Save(@"D:\yourpath\newfile.xml");
问题是表达式xmldoc.DocumentElement.ChildNodes[0]
选择了没有属性的
节点
不能更改不存在的属性
如果要更改
的“id”属性,需要在DocumentElement上执行此操作:
xmldoc.DocumentElement.Attributes["id"].Value = "Umaid";
如果要更改
中的文本,请执行以下操作:
XmlNode itemNode = xmldoc.SelectSingleNode("/rule/one-of/item");
if(itemNode != null)
{
itemNode.InnerText = "Umaid";
}
Marc您真正想用XML做什么??您要更改哪个属性 一个提示:您可以直接加载XmlDocument并将其保存到一个路径中—无需filestream
xmldoc.Load(@"D:\yourpath\file.xml");
xmldoc.Save(@"D:\yourpath\newfile.xml");
问题是表达式xmldoc.DocumentElement.ChildNodes[0]
选择了没有属性的
节点
不能更改不存在的属性
如果要更改
的“id”属性,需要在DocumentElement上执行此操作:
xmldoc.DocumentElement.Attributes["id"].Value = "Umaid";
如果要更改
中的文本,请执行以下操作:
XmlNode itemNode = xmldoc.SelectSingleNode("/rule/one-of/item");
if(itemNode != null)
{
itemNode.InnerText = "Umaid";
}
马克