Search code examples
c#string-parsing

String parsing (splitting and retrieving parameters)


I have a string formatted this way:

<?TAG param1="val1" parm2="val2" paramN="valN"  /><?TAG param1="val1" parm2="val2" paramN="valN"/><?TAG param1="val1" parm2="val2" paramN="valN"/>

"TAG" is always the same value, but number of occurrences is variable and the number of parameters for each occurrence too. I can't change the source format.

I need to get the list of parameters for each occurrence using C# (.NET 4.0) Can you help me out?


Solution

  • XElement rootElement = XElement.Parse(string.Format("<element>{0}</element>", 
                                                 yourString.Replace("?TAG", "TAG")));
    var elements = rootElement.Elements();
    var yourResult = elements.Select(x => new TagsAndParams { Tag = x,
        Params = x.Attributes.Where(xa => xa.Name.LocalName.BeginsWith("param") });
    

    With this class as a result holder (I know I could use anonymous types, but this is better for passing to other functions):

    public class TagsAndParams
    {
        XElement Tag;
        IEnumerable<XAttribute> Params;
    }