1

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;
            }
        }
    }
}
1
  • You're iterating over all the PlannedAbsences nodes in the document. The StartTime attribute isn't on PlannedAbsences, it's on Absence. Commented Oct 19, 2018 at 20:10

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

6 Comments

I get 'XmlDocument' does not contain a definition for 'Element'.
Check that you have the System.Xml.Linq namespace added. The xmlDoc variable should be a XDocument type. I'll edit my answer to address this.
I added the System.Xml.Linq namespace and tried the updated XDocument code but I still get the same erorr "XmlDocument does not contain a definition for Element'. I'm trying to sift through the code of another project that should be calling the same end point and doing something similar to see if I missed something.
It might be worth a try using the entire namespace in the variable declaration XDocument.Load to System.Xml.Linq.XDocument.Load. There could be another reference with a XDocument type.
The answer suggests using XDocument, not XmlDocument. They are different classes.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.