Programming Newbie Programming Newbie - 1 year ago 110
C# Question

Get attribute values from XML

This is my XML string.

<?xml version="1.0" encoding="UTF-8"?>
<Menu TextField="Menu" NavigateUrlField="/#" MenuID="74">
<Menu TextField="Assets" NavigateUrlField="/Assets" MenuID="1870" />
<Menu TextField="Asset Category" NavigateUrlField="/AssetCategory" MenuID="1871" />
<Menu TextField="Asset Location" NavigateUrlField="/AssetLocation" MenuID="1872" />

I need to get the TextField and MenuId from this XML. Only from Menu tag that is below root Menu tag.

Text Field MenuId
Assets 1870
Asset Category 1871
Asset Location 1872

I tried below code which is throwing "Object reference not set to an instance of an object.":

var xmlDoc = new XmlDocument();

XmlNodeList elemList = xmlDoc.GetElementsByTagName("Menu");
for (int i = 0; i < elemList.Count; i++)
string menuId = elemList[i].Attributes["MenuId"].Value;
string textField = elemList[i].Attributes["TextField"].Value;

Please someone help me.

Answer Source

Using xml linq :

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

namespace ConsoleApplication1
    class Program
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
            XDocument doc = XDocument.Load(FILENAME);
            XElement menu = doc.Element("Menu");
            var results = menu.Descendants("Menu").Select(x => new {
                textField = (string)x.Attribute("TextField"),
                menuID = (int)x.Attribute("MenuID")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download