我正在编写一个使用一些资源的小型Windows窗体应用程序(在C#中)。其中一个资源是XML文件。
应该在初始化第一个Form之前读取此XML文件。 XML文件的内容用于创建应用程序使用的对象。
通常我会在Visual Studio中将此XML文件添加为资源。
项目属性>资源>文件>添加现有文件
然后在应用程序中,我可以使用:XDocument.Parse(Resources.NameOfXMLResource)
在这个应用程序中,我希望能够添加或更新对象,这也应该更新XML文件中存储的信息。我知道我无法将更新的XML文件保存到Resources.NameOfXMLResource
,因为它实际上是一个包含XML文件所有内容的字符串。
我在C#项目中看到很多关于XML作为资源的帖子,但大多数帖子只是关于从资源中读取而不是写入它。
所以我的问题是:如何设置XML文件..
或
我目前读取/写入XML文件的代码:
this.file = Resources.XMLItemList;
public List<ItemModel> GetStoredItems()
{
return (from item in XDocument.Load(this.file).Descendants("Item")
select new ItemModel
{
Name = item.Attribute("Name").Value,
ID = item.Element("ID").Value,
Description = item.Element("Description").Value,
Size = Convert.ToInt32(item.Element("Size").Value),
Path = item.Element("Path").Value
}).ToList();
}
public string AddItem(ItemModel item)
{
try
{
var xdoc = XDocument.Load(this.file);
xdoc.Element("Items").Add(new XElement("Item",
new XAttribute("Name", item.Name),
new XElement("ID", item.ID),
new XElement("Description", item.Description),
new XElement("Size", item.Size),
new XElement("Path", item.Path)));
xdoc.Save(this.file);
return null;
}
catch (Exception ex)
{
return string.Format(Resources.ErrCanNotAddItemToXML, ex);
}
}