14

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"?

13
  • 1
    what do you mean by name? what should be the name of "Some text" ? it isn't an element so it doesn't have a name. Jan 3, 2015 at 20:25
  • Name of tag )element, node) is "title". I need that in my code, but XNode has no property of type XName.
    – Croll
    Jan 3, 2015 at 20:26
  • you mean you need to get "title" from "Some Text" ? Jan 3, 2015 at 20:27
  • 1
    well then don't use Nodes if you dont wanna work with Nodes, use Elements or Descendants methods. Jan 3, 2015 at 20:32
  • 2
    no title has nothing to do with that. title is another node, it's an element node and completely separate node from the "Some Text". it's just the parent node of the "Some Text". So it has a name because it's an Element. A text node does not have any name. Jan 3, 2015 at 20:41

2 Answers 2

25

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>.

1
  • and what if you want iterate all nodes, include text, and if its an element you want know his name?
    – dovid
    Jun 6, 2019 at 13:21
-1

if you have a node of element type, you can cast it:

if (node.NodeType == XmlNodeType.Element) {
    var el = (XElement)node;
    Console.WriteLine(el.Name);
}
1
  • Find any open XML dataset, write nested loop with your code, and you will provide yourself with anything necessary.
    – Croll
    Jun 6, 2019 at 17:27

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.