onTheInternet
onTheInternet

Reputation: 7253

GetElementByTagName returns System.Xml.XmlElementList

I have an XML document that looks like this

<?xml version="1.0" encoding="utf-8" ?>
<event>
  <name>Test Event</name>
  <date>07/09/1997</date>
  <description>Birthday</description>
  <blogURL></blogURL>
</event>

I want to grab these fields and display them in ASP:Labels

This is my code behind

    protected void Page_Load(object sender, EventArgs e)
    {
        XmlDocument pressRelease = new XmlDocument();
        pressRelease.Load(Server.MapPath("~/PressSection.xml"));

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

But this is what it displays in the label

System.Xml.XmlElementList

Not really sure what I'm doing wrong.

Upvotes: 0

Views: 1205

Answers (3)

Charles Mager
Charles Mager

Reputation: 26213

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();

Upvotes: 1

simme
simme

Reputation: 1554

This is actually the intended behavior.

The reason for it is that it returns a list of all elements that match your criteria. If you know for sure that you'll always want the first element, you could always get the first element by:

name[0].ToString()

However, you might also want to add some null and empty checking for the XmlElementList as it may also be empty, which will result in you getting a null pointer exception if you try to get an item from it.

Upvotes: 0

Mostafiz
Mostafiz

Reputation: 7352

try this way

XDocument doc = XDocument.Load(Server.MapPath("~/PressSection.xml"));
var query = doc.Descendants("event").Elements("name").FirstOrDefault();

Console.WriteLine(query.Value);

Upvotes: 0

Related Questions