来自xml的第一个节点

时间:2011-12-27 04:46:46

标签: c# 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循环,即使我确实知道它只运行一次。有更清洁的方法吗?

5 个答案:

答案 0 :(得分:1)

在没有for循环的情况下执行此操作的“现代”方法是使用LINQ to XML编写代码。

如果您确定XML文件中至少有一本书,则此代码将起作用。它会创建一个包含3个属性的匿名类型IdAuthorTitle

using System.Linq; // requires assembly reference to System.Core.dll
using System.Xml.Linq; // requires assembly reference to System.Xml.Linq.dll

// ...

XDocument document = XDocument.Load("yourfile.xml");
var book =
    (from b in document.Descendants("book")
    select new
    {
        Id = b.Attribute("id").Value,
        Author = b.Element("author").Value,
        Title = b.Element("title").Value
    }).First();

答案 1 :(得分:0)

是的,你可以使用XPATH。

例如,路径为

/catalog/book[1]/author

答案 2 :(得分:0)

如果您只是想直接查找“book.title”...或所有图书标题......

您可以考虑使用XPath(开放标准)和/或LINQ(仅限Microsoft):

http://msdn.microsoft.com/en-us/library/bb882630%28v=vs.90%29.aspx

http://msdn.microsoft.com/en-us/library/windows/desktop/ms753820%28v=vs.85%29.aspx

http://www.codeproject.com/KB/cpp/myXPath.aspx

答案 3 :(得分:0)

您可以尝试使用Linq XML(Import System.Xml.Linq)。

例如,

 XDocument doc = XDocument.Load(file);
 var nodeList = from ele in doc.Descendants("book")
                select new
                  {
                   ID=(string)ele.Attribute("id"),
                   Author=(string)ele.Element("author")
                   }; // Or use FirstOrDefault(); to obtain first node
 foreach (var t in nodeList)
  {
     Console.WriteLine(t.ID + " " + t.Author );
  }

答案 4 :(得分:0)

由于标记为C#,假设您至少拥有.NET 3.5,那么linq-to-xml可能最简单(至少恕我直言)

using System;
using System.Xml.Linq;

class Program
{
    static void Main(string[] args)
    {
        var 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>";
        XElement e = XElement.Parse(xml);

        var books = e.Elements("book");

        foreach (var book in books)
        {
            var title = book.Element("title").Value;
            var author = book.Element("author").Value;
            var isbn = book.Attribute("id").Value;

            Console.WriteLine("{0} ({1}) is written by {2}", title, isbn, author);
        }
    }
}