我试图弄清楚如何更新我的XML文件。我知道如何阅读和写作,但不知道如何更新现有记录。
我的XML文件如下:
<?xml version="1.0" standalone="yes"?>
<Categories>
<Category>
<CategoryId>1</CategoryId>
<CategoryName>Ayourvedic</CategoryName>
</Category>
<Category>
<CategoryId>2</CategoryId>
<CategoryName>Daily Needs</CategoryName>
</Category>
<Category>
<CategoryId>3</CategoryId>
<CategoryName>Clothes</CategoryName>
</Category>
<Category>
<CategoryId>4</CategoryId>
<CategoryName>Shops</CategoryName>
</Category>
<Category>
<CategoryId>5</CategoryId>
<CategoryName>daily use product</CategoryName>
</Category>
</Categories>
和 这就是我写文件的方式:
private void btnUpdate_Click(object sender, EventArgs e)
{
XmlDocument xdoc = new XmlDocument();
string PATH = "xmldata.xml";
XElement xElement;
xElement = new XElement("Category");
XElement element = new XElement(
"Category",
new XAttribute("CategoryId", CategoryId),
new XAttribute("CategoryName", CategoryName)
);
xElement.Add(element);
xElement.Save("PATH");
}
但我的代码无效,请任何人都可以提供一些想法或解决方案。
答案 0 :(得分:1)
使用System.Xml以下代码可以提供帮助:
static void Main(string[] args)
{
String inputfile = @"D:\Temp\cat.xml";
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(inputfile);
XmlNode root = xmldoc.DocumentElement;
//Method 1
XmlElement category = xmldoc.CreateElement("Category");
XmlElement catid = xmldoc.CreateElement("CategoryId");
XmlElement catname = xmldoc.CreateElement("CategoryName");
catid.InnerText = "6";
catname.InnerText = "The newly added category";
category.AppendChild(catid);
category.AppendChild(catname);
root.AppendChild(category);
//Method 2
XmlElement category2 = xmldoc.CreateElement("Category");
String catdata = String.Format("<CategoryId>{0}</CategoryId><CategoryName>{1}</CategoryName>", "7", "Adding data by innerXML");
category2.InnerXml = catdata;
root.AppendChild(category2);
xmldoc.Save(inputfile);
}
如需进一步阅读,请参阅XmlDocument和XmlNode
使用System.Linq.Xml以下内容应有所帮助:
static void Main(string[] args)
{
String inputfile = @"D:\Temp\cat.xml";
XDocument xmldoc = XDocument.Load(inputfile);
XElement root = xmldoc.Root;
root.Add(new XElement("Category", new XElement("CategoryId", "8"), new XElement("CategoryName", "Added by LinqXML")));
xmldoc.Save(inputfile);
}
您也可以参考this answer。
编辑:如何更改元素的值
static void Main(string[] args)
{
String inputfile = @"D:\Temp\cat.xml";
XDocument xmldoc = XDocument.Load(inputfile);
XElement root = xmldoc.Root;
String val = "5";
IEnumerable<XElement> vls = from e in root.Elements("Category") where e.Element("CategoryId").Value.Equals(val) select e;
if (vls.Count() == 1)
{
vls.ElementAt(0).Element("CategoryName").Value = "Value has been changed";
}
xmldoc.Save(inputfile);
}
要进一步了解,请参阅this link。