gpt4 book ai didi

c# - 使用 XmlSerialize 反序列化集合会导致集合为空

转载 作者:行者123 更新时间:2023-11-30 22:32:13 25 4
gpt4 key购买 nike

我正在尝试反序列化以下 XML 文档:

<?xml version="1.0" encoding="utf-8" ?>
<TestPrice>
<Price>
<A>A</A>
<B>B</B>
<C>C</C>
<Intervals>
<Interval>
<A>A</A>
<B>B</B>
<C>C</C>
</Interval>
<Interval>
<A>A</A>
<B>B</B>
<C>C</C>
</Interval>
</Intervals>
</Price>
</TestPrice>

我定义了三个类来将其反序列化为对象图:

public class TestPrice
{
private List<Price> _prices = new List<Price>();
public List<Price> Price
{
get { return _prices; }
set { _prices = value; }
}
}

public class Price
{
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }

private List<Interval> _intervals = new List<Interval>();
public List<Interval> Intervals
{
get { return _intervals; }
set { _intervals = value; }
}
}

public class Interval
{
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
}

我可以反序列化每个部分。也就是说,我可以这样做:

var serializer = new XmlSerializer(typeof(Price));
var priceEntity = ((Price)(serializer.Deserialize(XmlReader.Create(stringReader))));

priceEntity使用 stringReader 中包含的 XML 数据正确初始化,包括 List<Interval> Intervals .但是,如果我尝试反序列化 TestPrice例如,它总是出现一个空的 List<Price> Price .

如果我改变 TestPrice 的定义像这样:

public class TestPrice
{
public Price Price { get; set; }
}

它有效。但当然我的 XSD 将价格定义为一个序列。我有其他实体反序列化得很好,但它们不在根元素中包含序列。有没有我不知道的限制?我应该在 TestPrice 中包含某种元数据吗? ?

最佳答案

只需使用 [XmlElement] 装饰您的 Price 集合:

[XmlElement(ElementName = "Price")]
public List<Price> Price
{
get { return _prices; }
set { _prices = value; }
}

您似乎也在反序列化 Price,而您的 XML 中的根标记是 TestPrice。所以,这是一个完整的例子:

public class TestPrice
{
[XmlElement(ElementName = "Price")]
public List<Price> Price { get; set; }
}

public class Price
{
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }

public List<Interval> Intervals { get; set; }
}

public class Interval
{
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
}

class Program
{
static void Main()
{
var xml = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<TestPrice>
<Price>
<A>A</A>
<B>B</B>
<C>C</C>
<Intervals>
<Interval>
<A>A</A>
<B>B</B>
<C>C</C>
</Interval>
<Interval>
<A>A</A>
<B>B</B>
<C>C</C>
</Interval>
</Intervals>
</Price>
</TestPrice>";

var serializer = new XmlSerializer(typeof(TestPrice));
using (var reader = new StringReader(xml))
using (var xmlReader = XmlReader.Create(reader))
{
var priceEntity = (TestPrice)serializer.Deserialize(xmlReader);
foreach (var price in priceEntity.Price)
{
// do something with the price
}
}
}
}

关于c# - 使用 XmlSerialize 反序列化集合会导致集合为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8827063/

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