XML parsing using attributes

2019-08-05 13:19发布

I have XML-based config for application shortcuts bindings. i need to parse it.

<ShortcutBinding>
  <ShortcutHandler Name ="Retail.Application.Documents.Outcome.Presentation.OutcomePresenter">
    <Shortcut Name="EditHeader">
      <Key>CTRL</Key>
      <Key>F4</Key>
    </Shortcut>
    <Shortcut Name="EditItem">
      <Key>F4</Key>
    </Shortcut>
  </ShortcutHandler>  
</ShortcutBinding>

I know that .Net has attributes for deserializing XML into objects. Can anyone write complete example for such deserialization, using attributes.

1条回答
在下西门庆
2楼-- · 2019-08-05 13:38
public class ShortcutBinding
{
    public ShortcutHandler ShortcutHandler { get; set; }
}

public class ShortcutHandler
{
    [XmlAttribute]
    public string Name { get; set; }

    [XmlElement("Shortcut")]
    public List<Shortcut> Shortcuts { get; set; }
}

public class Shortcut
{
    [XmlAttribute]
    public string Name { get; set; }

    [XmlElement("Key")]
    public List<string> Keys { get; set; }
}

Deserializing:

XmlSerializer serializer = new XmlSerializer(typeof(ShortcutBinding));
var binding = (ShortcutBinding)serializer.Deserialize(XmlReader.Create(path));
查看更多
登录 后发表回答