How to read namespace based xml using Linq

In this post, I will show you how to read XML with the namespace. For this demo, I will use the following XML structure

<?xml version="1.0" encoding="utf-8" ?>
<accounts xmlns="urn:account">
  <account>1001</account>
  <account>1002</account>
</accounts> 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace XLinq
{
    class Program {
        static void Main(string[] args)
        {
            var doc = XDocument.Load("accounts.xml");
            var query = from x in doc.Descendants("{urn:account}account")
                        select x;
            foreach (var item in query)
            {
                Console.WriteLine(item);
            }
        }
    }
}

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru