This is my xml file
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
</catalog>
And I need read the author name so this is what I do:
XmlNodeList bookList = doc.GetElementsByTagName("book");
foreach (XmlNode node in bookList)
{
XmlElement bookElement = (XmlElement)node;
string title = bookElement.GetElementsByTagName("title")[0].InnerText;
string author = bookElement.GetElementsByTagName("author")[0].InnerText;
string isbn = "";
if (bookElement.HasAttributes)
{
isbn = "";
; //bookElement.Attributes["ISBN"].InnerText
}
Console.WriteLine("{0} ({1}) is written by {2}\n", title, isbn, author);
}
I do not like to use a for loop even though I surely know that it would run only once. Is there a much cleaner method of doing this?
The “modern” way to do this without
forloops is to write code using LINQ to XML.This code will work if you are sure there is at least 1 book in the XML file. It creates an anonymous type with 3 properties,
Id,Author, andTitle.