Search code examples
c#xmllinq-to-xml

How to parse string XML and extract int values


What would be the simple way of parsing XML below which is of string datatype and get the IDs as array of int. Using C#.Net

   <IDs>
    <ID>1</ID>
    <ID>2</ID>
    <ID>3</ID>
    <ID>4</ID>
  </IDs>

Solution

  • There are many ways to do that, and for this simple case most of them would be as simple. For example using XDocument we can query <ID> using LINQ or XPath :

    var xml = @"<IDs>
        <ID>1</ID>
        <ID>2</ID>
        <ID>3</ID>
        <ID>4</ID>
      </IDs>";
    var doc = XDocument.Parse(xml);
    var idsFromLinq = doc.Root
                         .Elements("ID")
                         .Select(o => (int)o)
                         .ToList();
    var idsFromXPath = doc.XPathSelectElements("/IDs/ID")
                          .Select(o => (int)o)
                          .ToList();