在C#System.Xml.Serialization中序列化了一个XML数据。
有一个描述根元素的根类。它包含后代类(如Movie)中描述的List类型的文件。
我可以将我的XML文档反序列化为一个类,并使用List.Add或List.Insert在列表中添加一个新元素:
cfg.Movies.Insert(0, new Movie("Newly added: Pulp Fiction", "1994"));
但反向操作不起作用:
cfg.Movies.Remove(new Movie("To be removed: The Godfather", "1974"));
所以问题是如何从xml类列表中删除元素?
示例在这里:https://dotnetfiddle.net/WqCNoD
using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Xml.Serialization;
public class Program
{
public static void Main()
{
string xmlString =
@"<favorites>
<movies>
<movie title=""To be removed: The Godfather"" year=""1974"" />
<movie title=""The Terminator"" year=""1984"" />
<movie title=""Dark Knight"" year=""2008"" />
</movies>
<books>
<book title = ""1984"" author=""George Orwell"" />
<book title = ""Robinson Crusoe"" author=""Daniel Defoe "" />
<book title = ""Frankenstein"" author=""Mary Shelly"" />
</books>
<music>
<artist title = ""Beatles"" genre=""rock"" />
<artist title = ""Queen"" genre=""rock"" />
<artist title = ""Metallica"" rock=""heavy metal"" />
</music>
</favorites>";
XDocument xdoc = XDocument.Parse(xmlString);
var xdocData = xdoc.ToString();
//DeSerialization
XmlSerializer serializer = new XmlSerializer(typeof(Favorites));
using (StringReader reader = new StringReader(xdoc.ToString()))
{
Favorites cfg = (Favorites) serializer.Deserialize(reader);
// Add & remove element
cfg.Movies.Insert(0, new Movie("Newly added: Pulp Fiction", "1994"));
cfg.Movies.Remove(new Movie("To be removed: The Godfather", "1974"));
//Serialization
XmlSerializer serializer2 = new XmlSerializer(cfg.GetType());
using (StringWriter writer = new StringWriter())
{
serializer2.Serialize(writer, cfg);
Console.WriteLine(writer.ToString());
}
}
}
[XmlRoot(ElementName = "favorites", DataType = "string", IsNullable = true)]
public class Favorites
{
//public string Name { get; set; }
[XmlArray("movies")]
[XmlArrayItem("movie")]
public List<Movie> Movies { get; set; }
public Favorites()
{
Movies = new List<Movie>();
}
}
public class Movie
{
[XmlAttribute("title")]
public string Title { get; set; }
[XmlAttribute("year")]
public string Year { get; set; }
public Movie() { }
public Movie(string title, string year)
{
Title = title;
Year = year;
}
}
}
答案 0 :(得分:2)
创建新对象时,其引用尚未在列表中。您需要在列表中搜索要删除的项目,然后使用搜索结果将其删除。
类似的东西:
var movieToRemove = cfg.Movies.SingleOrDefault(m => m.Title == "To be removed: The Godfather" && m.Year == "1974");
if (moveiToRemove != null)
cfg.Movies.Remove(movieToRemove);
答案 1 :(得分:1)
您正在尝试删除新电影而不是您反序列化的电影。
您必须先在列表中找到该电影,然后将其删除。
替换
cfg.Movies.Remove(new Movie("To be removed: The Godfather", "1974"));
使用
cfg.Movies.Remove(cfg.Movies.Find(x => x.Title == "Newly added: Pulp Fiction"));