0

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" />
</Menu>

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 but not working:

var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);

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.

good-to-know
  • 742
  • 3
  • 15
  • 32

3 Answers3

1

Please pay attention, to you attribute name "MenuID", not "MenuId"

XmlNode root = xmlDoc.DocumentElement;
XmlNodeList elemList = root.SelectNodes("Menu");
for (int i = 0; i < elemList.Count; i++)
{       
    string menuId = elemList[i].Attributes["MenuID"].Value;
    string textField = elemList[i].Attributes["TextField"].Value;
}
Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49
  • Holy cow, only 1 out of 6 answers that explains what is actually wrong and not rewriting the whole code. Keep on doing good work! – Thomas Weller Nov 30 '16 at 08:03
0

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")
            }).ToList();
        }
    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20
-1

You can use a simple XPath query to find the Menu at parent level and then select all Menu nodes below it:

XmlNodeList elemList = xmlDoc.SelectNodes("Menu/Menu");

Then also change Attributes["MenuId"].Value to Attributes["MenuID"].Value because all names are case sensitive in XML.

Peter B
  • 22,460
  • 5
  • 32
  • 69
  • Did someone by accident lean on the downvote button? My solution works, I actually tested it, so why? – Peter B Nov 30 '16 at 13:06