Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get name of System.Xml.Linq.XNode?

Tags:

c#

casting

xml

Each XML element, like <title /> has a name - "title". I use foreach to enumerate items supplied by XNode.Nodes() method and handle each of them by tag name.

I cast XNode to XElement, to access XElement.Name.LocalName property to get tag name, like "title".

foreach(XElement as_element in doc.Nodes())

Problem has appeared after i have tried parsing this tag:

<title>"Some text"</title>

Now its type is XText (: XNode), and i cannot cast it to XElement. I get an InvalidCastException. How can i get XNode's "name"?

like image 305
Croll Avatar asked Jan 03 '15 20:01

Croll


1 Answers

INode does not always have a name. It's better to use Elements() instead of Nodes(), to enumerate child elements inside XElement, then we have a IEnumerable<XElement>.

like image 181
Croll Avatar answered Oct 05 '22 15:10

Croll