gpt4 book ai didi

c# - 反序列化 xmlarray 的 xml 属性

转载 作者:太空宇宙 更新时间:2023-11-03 21:44:11 27 4
gpt4 key购买 nike

我知道您不能向 XmlArray 添加属性,我认为这真的很不方便。我知道我可以为 Phone 创建一个单独的类,但是,Phone 属于 Access。我还有大约 30 个节点正在访问中。如何反序列化属性 hasTextField?

    <Access>
<Phone hasTextField="true">
<Item description="Skype" />
<Item description="IP Phone" />
</Phone>
<Computer>
<Item description="PC" />
<Item description="Laptop" />
</Computer>
</Access>


[XmlRoot("Access")]

public class Access
{
public Access(){}

[XmlArray("Phone")]
[XmlArrayItem("Item")]
public AccessItem[] ItemList;

[XmlArray("Computer")]
[XmlArrayItem("Item")]
public AccessItem[] ItemList;
}

最佳答案

您可以将 XmlArray 替换为 XmlElement

参见:How to add an attribute to a collection marked with XmlArrayAttribute?

[XmlType("Access")]
public class Access
{
[XmlElement("Phone")]
public AccessItem Phone { get; set; }

[XmlElement("Computer")]
public AccessItem Computer { get; set; }
}

public class AccessItem
{
public AccessItem()
{
Items = new List<Item>();
}

[XmlAttribute("hasTextField")]
public bool HasTextField { get; set; }

[XmlElement("Item")]
public List<Item> Items { get; set; }
}

[XmlType("Item")]
public class Item
{
[XmlAttribute("description")]
public string Description { get; set; }
}

代码:

var data = @"<Access>
<Phone hasTextField=""true"">
<Item description=""Skype"" />
<Item description=""IP Phone"" />
</Phone>
<Computer>
<Item description=""PC"" />
<Item description=""Laptop"" />
</Computer>
</Access>";

var serializer = new XmlSerializer(typeof(Access));

Access access;

using(var stream = new StringReader(data))
using(var reader = XmlReader.Create(stream))
{
access = (Access)serializer.Deserialize(reader);
}

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

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