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

标签 c# xml

我知道您不能向 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/

相关文章:

c# - 检索 Windows Phone 中的设备信息

c# - 如何在 Linux 中使用 libusb 获取设备路径

变量周围的 C++ 堆栈已损坏

python - xml.etree.ElementTree 与 lxml.etree : different internal node representation?

java - 具有可变数量 @XMLElements 的 JAXB

java - 如何在java中使用xerces?

c# - 使用 AWS 低级 API 将 null AttributeValue 传递到 DynamoDb

c# - 如何从文件中获取唯一的文件标识符

c# - EMGU CV 2.4.9 人脸识别精度问题

xml - 如何比较xsl中的日期