XML parsing using XElement

It seems I can't find how to properly parse this with XElement:

<messages>
  <message subclass="a" context="d" key="g">
  <message subclass="b" context="e" key="h">
  <message subclass="c" context="f" key="i">
</messages>

I would like to get this in a list where there are three subclasses of the string, context, key.

+5
source share
1 answer

Your input is not valid XML, it has no closing tags for the internal elements of the message. But provided that the format is valid, you can analyze your structure, as in:

string xml = @"<messages> 
                  <message subclass=""a"" context=""d"" key=""g""/> 
                  <message subclass=""b"" context=""e"" key=""h""/> 
                  <message subclass=""c"" context=""f"" key=""i""/> 
               </messages>";

var messagesElement = XElement.Parse(xml);
var messagesList = (from message in messagesElement.Elements("message")
                   select new 
                    {
                        Subclass = message.Attribute("subclass").Value,
                        Context = message.Attribute("context").Value,
                        Key = message.Attribute("key").Value
                    }).ToList();

You can also use XDocumentfor a complete XML document and use the method Loadinstead Parseif you used an XML file or stream, for example. In addition, you can select a specific class if you have a specific one. Given a class definition

class Message 
{
    public string Subclass { get; set; }
    public string Context { get; set; } 
    public string Key { get; set; }
}

select new Message , List<Message>, .

+23

All Articles