gpt4 book ai didi

c# - 从类中的列表属性中删除元素

转载 作者:太空宇宙 更新时间:2023-11-03 22:46:01 26 4
gpt4 key购买 nike

在C# System.Xml.Serialization中有一个序列化的XML数据。

有一个描述根元素的根类。它包含子类(如电影)中描述的列表类型的文件。

我可以将我的 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;
}
}
}

最佳答案

当您创建一个新对象时,它的引用还不在列表中。您需要在列表中搜索要删除的项目,然后使用搜索结果将其删除。

类似于:

var movieToRemove = cfg.Movies.SingleOrDefault(m => m.Title == "To be removed: The Godfather" && m.Year == "1974");
if (moveiToRemove != null)
cfg.Movies.Remove(movieToRemove);

关于c# - 从类中的列表属性中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49882776/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com