gpt4 book ai didi

c# - 如何在 C# 对象中反序列化这个嵌套的 xml

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

我正在使用 silverlight ot 实现 xml 的反序列化,如下所示:

字符串 xmlString=

<attributes>
<value>1</value>
<showstatus>yes</showstatus>
<disableothers>
<disableother>
<disablevalue>1</disablevalue>
<todisable>skew</todisable>
<todisable>skew_side</todisable>
</disableother>
<disableother>
<disablevalue>0</disablevalue>
<todisable>automodel</todisable>
</disableother>
</disableothers>
</attributes>

在我尝试实现这一目标的过程中,我觉得我在类里面有所收获。类如下:

 [XmlRoot(ElementName = "attributes")]
public class Attributes
{
[XmlElement("disableOthers")]
public List<DisableOthers> DisableOthers { get; set; }
}



[XmlRoot(ElementName = "disableOthers")]
public class DisableOthers
{
[XmlElement("disableOthers")]
public List<DisableOther> DisableOther { get; set; }
}


[XmlRoot(ElementName = "disableOther")]
public class DisableOther
{
[XmlElement("disablingitem")]
public int DisablingItem { get; set; }

[XmlElement("todisable")]
public int ToDisable { get; set; }

[XmlElement("disablevalue")]
public int DisableValue { get; set; }
}

如果我的类与给定的 xml 对应是正确的,有人可以纠正我吗?会有很大帮助。

注意:确切的问题是当我创建父类的对象时它给出“0”值。 我已经尝试过了,然后我在 stackoverflow 上来到这里。

最佳答案

您不需要 DisableOthers 类。只需将属性与 XmlArrayItem 属性一起使用:

[XmlArrayItem("disableother", IsNullable=false)]
[XmlArray("disableOthers")]
public DisableOther[] DisableOthers { get; set; }

完整的映射如下:

[XmlRoot("attributes")]    
public class Attributes
{
[XmlElement("value")]
public byte Value { get; set; }

[XmlElement("showstatus")]
public string ShowStatus { get; set; }

[XmlArray("disableothers")]
[XmlArrayItem("disableother", IsNullable = false)]
public DisableOther[] DisableOthers { get; set; }
}

[XmlRoot("disableOther")]
public class DisableOther
{
[XmlElement("disablevalue")]
public byte DisableValue { get; set; }

[XmlElement("todisable")]
public string[] ToDisable { get; set; }
}

反序列化:

XmlSerializer serializer = new XmlSerializer(typeof(Attributes));
using (var reader = new StringReader(xmlString))
{
var attributes = (Attributes)serializer.Deserialize(reader);
attributes.Dump();
}

输出:

{
Value: 1,
ShowStatus: "yes",
DisableOthers: [
{
DisableValue: 1,
ToDisable: [ "skew", "skew_side" ]
},
{
DisableValue: 0,
ToDisable: [ "automodel" ]
}
]
}

关于c# - 如何在 C# 对象中反序列化这个嵌套的 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24032782/

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