onTheInternet onTheInternet - 5 months ago 34
ASP.NET (C#) Question

GetElementByTagName returns System.Xml.XmlElementList

I have an XML document that looks like this

<?xml version="1.0" encoding="utf-8" ?>
<name>Test Event</name>

I want to grab these fields and display them in

This is my code behind

protected void Page_Load(object sender, EventArgs e)
XmlDocument pressRelease = new XmlDocument();

XmlNodeList name = pressRelease.GetElementsByTagName("name");
CurrentEventName.Text = name.ToString();

But this is what it displays in the label


Not really sure what I'm doing wrong.


As the name might suggest and, as the documentation tells you, the method returns:

An XmlNodeList containing a list of all matching nodes. If no nodes match name, the returned collection will be empty.

You need to iterate that list, or simply take the first item if you're sure one will always be there:

var names = pressRelease.GetElementsByTagName("name");
CurrentEventName.Text = names[0].Value;

That said, LINQ to XML is a far nicer API, I would definitely encourage you to learn more about it:

var doc = XDocument.Load(Server.MapPath("~/PressSection.xml"));
CurrentEventName.Text = (string)doc.Descendants("name").Single();