C# 如何使用 XmlSerializer 反序列化为 List<String>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1208643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:57:29  来源:igfitidea点击:

How to deserialize into a List<String> using the XmlSerializer

c#xml-serialization

提问by Russ Clark

I'm trying to deserialize the XML below into class, with the Componentsdeserialized into a List<string>, but can't figure out how to do so. The deserializer is working fine for all the other properties, but not Components. Anyone know how to do this?

我正在尝试将下面的 XML 反序列化为类,Components反序列化为 a List<string>,但不知道该怎么做。解串器适用于所有其他属性,但不适用于Components. 有人知道怎么做吗?

<ArsAction>
  <CustomerName>Joe Smith</CustomerName>
  <LoginID>jdsmith</LoginID>
  <TicketGroup>DMS</TicketGroup>
  <Software>Visio 2007 Pro</Software>
  <Components>
    <Component>Component 1</Component>
    <Component>Component 2</Component>
  </Components>
  <Bldg>887</Bldg>
  <Room>1320p</Room>
</ArsAction>

采纳答案by Brian Ensink

Add a property like this to hold the list of Components:

添加一个像这样的属性来保存组件列表:

[XmlArray()]
public List<Component> Components { get; set; }

Edit: Sorry I misread that. You want to read it into a collection of strings. I just tried this below and it worked on your sample. The key is just to setup the correct xml serialization attributes.

编辑:对不起,我误读了。您想将其读入字符串集合。我只是在下面试过这个,它对你的样本有效。关键只是设置正确的 xml 序列化属性。

public class ArsAction
{
    [XmlArray]
    [XmlArrayItem(ElementName="Component")]
    public List<string> Components { get; set; }
}