question

CoreyFleig-6304 avatar image
0 Votes"
CoreyFleig-6304 asked YitzhakKhabinsky-0887 commented

How to get the name of a node in XML

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-wpfdotnet-wpf-xaml
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@CoreyFleig-6304,

You are using somewhat antiquated API.

The preferred API to handle XML is LINQ to XML. It is available in the .Net Framework since 2007.

0 Votes 0 ·
PeterFleischer-3316 avatar image
0 Votes"
PeterFleischer-3316 answered

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);
     }
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

YitzhakKhabinsky-0887 avatar image
0 Votes"
YitzhakKhabinsky-0887 answered YitzhakKhabinsky-0887 commented

Hi @CoreyFleig-6304,

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);
 }
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks Isaac! I'm just learning XML processing, so I went with what I thought was a simpler version.
I don't know LINQ yet, but now that you've shown me this, I'm very interested!

Corey

0 Votes 0 ·

@CoreyFleig-6304,

Good to hear from you.

LINQ to XML is much simpler and more poweful.
LINQ to XML API basically replaced the ancient XML API you went with.
It happened long time ago in 2007.

0 Votes 0 ·