65.9K
CodeProject is changing. Read more.
Home

Read XML with Namespace resolution using XLinq.XElement

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.67/5 (11 votes)

Nov 13, 2008

CPOL
viewsIcon

73483

Read XML with Namespace resolution using XLinq.XElement

Introduction

This article demonstrates how to read a xml which has several namespaces via XElement. This is a easy day to day activity which is not so obvious, so writing a small snippet for helping developers.

Background

XML Namespaces are used to identify a domain for a tag. So if a xml is a mix of xml's from two different places and have same tag name, then parsers can understand that the tag belongs to which domain. In this article we will help parser by specifying the namespace while reading.

Using the code

After reading the background, code should be very easy to understand. If we do not supply a namespace to obtain element, parser would not be able to understand the tag's origin and so will not be able to obtain the result. If we are reading a XML which has a namespace then we must resolve the same.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace XElementReading
{
    class Program
    {
        static string myxml =
            @"<root>
                <one xmlns:a='http://rediff.com'>
                    <a:oneone xmlns:b='http://yahoo.com'>
                        <b:id>1</b:id>
                        <b:name></b:name>
                    </a:oneone>
                    <a:twotwo xmlns:b='http://orkut.com'>
                        <b:id>1</b:id>
                        <b:name></b:name>
                    </a:twotwo>
                </one>
              </root>";

        static void Main(string[] args)
        {
            XElement elem = XElement.Parse(myxml);

            XNamespace nsr = "http://rediff.com";
            XNamespace nsy = "http://yahoo.com";

            string t = elem.Element("one").Element(nsr + "oneone").Element(nsy + "id").Value;

	    Console.WriteLine("Value of id within oneone: {0}", t);	
            Console.ReadLine();
        }
    }
}

Points of Interest

This snippet helps us understand the necessity of namespaces and XML parsers need for a namespace.

History

None.