Это мой XML-файлпервый узел из XML
<?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>
И мне нужно прочитать имя автора, так это то, что я делаю:
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);
}
Я не люблю использовать for
цикл даже хотя я точно знаю, что он будет работать только один раз. Есть ли более чистый способ сделать это?
вы можете использовать первый индекс Booklist как 'XmlElement bookElement = (XmlElement) bookList [0];', а затем вы можете удалить forloop –