Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading values from within an XNode

Tags:

c#

xml

linq

I have some code that is returning a XNode to me which looks like this:

<File>
  <Component>Main</Component>
  <Path>C:\Main\</Path>
  <FileName>main.txt</FileName>
</File>

I need to have some C# code that will be able to pull out the value of Path for example (C:\Main). I know that if I was using an XML node I could do it like this:

String filePath = xmlNode["Path"].InnerText;

Does anybody know what the equivalent would be for an XNode? Any help is much appreciated!

like image 412
DukeOfMarmalade Avatar asked Nov 10 '11 09:11

DukeOfMarmalade


3 Answers

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.

like image 148
Jon Skeet Avatar answered Oct 18 '22 14:10

Jon Skeet


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;
like image 27
Giu Avatar answered Oct 18 '22 16:10

Giu


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;
like image 1
Michael_S_ Avatar answered Oct 18 '22 15:10

Michael_S_