Reading values from within an XNode

You can convert your XNode into XElement to access to its properties, my example:

XNode lastNode = myXElement.LastNode;

//if I want to get the 'ID' attribute
string id = (lastNode as XElement).Attribute("ID").Value;

Casting XNode to XElement works for the individual element to retrieve its value or attributes. But you won't be able to use myXelement.Elements("XXX") to get nested elements. For that you can use xmlNode.Nodes().

This should work:

var nodes = xmlNode.Nodes();//Get all nodes under 'File'
var fileNameNode = nodes.Where(el => ((XElement)el).Name.LocalName == "FileName")
.FirstOrDefault();
string filePath = ((XElement)fileNameNode).Value;

Do you have to have it returning an XNode rather than an XElement? With an XElement it's simpler than with an XNode:

string filePath = fileElement.Element("Path").Value;

That will find the first Path element, and will throw a NullReferenceException if there aren't any. An alternative if you're happy to get null if there aren't any would be:

string filePath = (string) fileElement.Element("Path");

If you're really stuck with XNode, you'll either have to cast to XElement or possibly XContainer.

Tags:

C#

Linq

Xml