How to get the name of a node in XML

Coreysan 1,696 Reputation points
2021-06-08T23:42:12.447+00:00

I'm learning to use C# to read an XML file. In specific, I use this line:

        XmlNodeList bookname = xmlDoc.GetElementsByTagName("book");

In the XML file, I have:

      <book name="Side-on Apparition">

So how can I get the book name of "Side-on Apparition" into a string?

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,771 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
809 questions
{count} votes

Accepted answer
  1. Peter Fleischer (former MVP) 19,321 Reputation points
    2021-06-09T05:07:57.043+00:00

    HI,
    assign Attribut from XmlElement in your bookname like in following code:

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load("Program39.xml");
    
        XmlNodeList booknames = xmlDoc.GetElementsByTagName("book");
        foreach (XmlElement item in booknames)
        {
          string name = item.GetAttribute("name");
          Console.WriteLine(name);
        }
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Yitzhak Khabinsky 25,856 Reputation points
    2021-06-09T13:43:24.487+00:00

    Hi @Coreysan ,

    LINQ to XML implementation.

    The provided XML is not well-formed. I had to fix it first.

    <book name="Side-on Apparition"/>  
    

    c#

    void Main()  
    {  
    	const string FILENAME = @"e:\Temp\CoreyFleig-6304.xml";  
    	XDocument xdoc = XDocument.Load(FILENAME);  
    	  
    	XElement xelem = xdoc.Descendants("book").FirstOrDefault();  
      
    	string bookname = xelem.Attribute("name").Value;  
    	Console.WriteLine("bookname attribute: '{0}'", bookname);  
    }  
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.