gpt4 book ai didi

c# - 反序列化没有属性的 XML

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

我有以下 XML,但我无法反序列化为我需要的对象。

<response>
<texts>
<text name="blabla">This is bla</text>
<text name="test xpto">This is a text</text>
(…)
</texts>
</response>

这是我到目前为止尝试过的:

public class ResponseTexts : Response
{
[XmlArray(ElementName = "texts")]
[XmlArrayItem(ElementName = "text"]
public List<Text> Texts { get; set; }
}

public class Text
{
[XmlElement(ElementName = "text")]
public string TextValue { get; set; }
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
}

但到目前为止,TextValue 始终为空....有人可以启发我吗?

提前致谢

最佳答案

您应该使用 XmlText 来获取元素值。这是正确的序列化属性:

[XmlRoot("response")]
public class Response
{
[XmlArray(ElementName = "texts")]
[XmlArrayItem(ElementName = "text")]
public List<Text> Texts { get; set; }
}

public class Text
{
[XmlText]
public string TextValue { get; set; }
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
}

反序列化:

var serializer = new XmlSerializer(typeof(Response));
using(var stream = File.OpenRead(path_to_xml))
{
var response = (Response)serializer.Deserialize(stream);
}

结果:

{
Texts: [
{ TextValue: "This is bla", Name: "blabla" },
{ TextValue: "This is a text", Name: "test xpto" }
]
}

关于c# - 反序列化没有属性的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22406473/

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