Caverman
Caverman

Reputation: 3727

XML Node Attribute returning as NULL when populated?

I have a XML Doc that I'm pulling out a specific Node and all of it's attributes. In debug mode I can see that I'm getting the specific Nodes and all of their attributes. However, when I try to get the attribute value it can't find it and returns a NULL value. I've done some searching and looked at some examples and from what I can tell I should be getting the value but I'm not and I don't see what I'm doing wrong.

I'm trying to get the StartTime value.

Here is the XML that is returned. enter image description here

Here you can see in debug and with the Text Visualizer the value should be there. enter image description here

The code I'm trying.

XmlNodeList nodes = xmlDoc.GetElementsByTagName("PlannedAbsences");
if (nodes != null && nodes.Count > 0)
{
    foreach (XmlNode node in nodes)
    {

        if (node.Attributes != null)
        {
            var nameAttribute = node.Attributes["StartTime"];
            if (nameAttribute != null)
            {
                //var startDate = nameAttribute.Value;
            }
        }
    }
}

Upvotes: 1

Views: 1257

Answers (1)

William
William

Reputation: 107

Using the XDocument class contained within the System.Xml.Linq namespace, grab the sub elements from the PlannedAbsences parent, then iterate over sub elements retrieving the value of the desired attribute.

var xmlDoc = XDocument.Load(@"path to xml file")
var absences = xmlDoc.Element("PlannedAbsences")?.Elements("Absence");
foreach (var item in absences)
{
    var xElement = item.Attribute("StartTime").Value;
    Console.WriteLine(xElement);
}

Upvotes: 1

Related Questions