gpt4 book ai didi

c# - 仅反序列化 XML 中的特定项目并添加到列表

转载 作者:数据小太阳 更新时间:2023-10-29 02:28:59 25 4
gpt4 key购买 nike

我有一个包含多个项目的 XML 文件,我想一次只反序列化一个特定的项目,而不是所有项目,然后将其添加到列表中。

使用 this site 中的示例,如何仅反序列化 Id=2Product 并将其添加到 productList

类:

public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}

代码:

void foo()
{
string xmlString = "<Products><Product><Id>1</Id><Name>My XML product</Name></Product><Product><Id>2</Id><Name>My second product</Name></Product></Products>";

XmlSerializer serializer = new XmlSerializer(typeof(List<Product>), new XmlRootAttribute("Products"));

StringReader stringReader = new StringReader(xmlString);

List<Product> productList = (List<Product>)serializer.Deserialize(stringReader);
}

最佳答案

您可以使用 XDocument 类来查询 Xml:

StringReader stringReader = new StringReader(xmlString);
XDocument document = XDocument.Load(stringReader);

var node = document.Descendants("Product").FirstOrDefault(p => p.Descendants("Id").First().Value == "2");
if(node != null)
{
XmlSerializer serializer = new XmlSerializer(typeof(Product));
var xmlReader = new StringReader(node.ToString());
Product result = serializer.Deserialize(xmlReader) as Product;
}

诚然,这是一个快速而肮脏的解决方案,在某些情况下可能需要进一步分析。

关于c# - 仅反序列化 XML 中的特定项目并添加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40007793/

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