我是XML的新手,对解析此类文件有疑问:
<?xml version="1.0" encoding="UTF-8"?>
<ISBNdb server_time="2005-07-29T02:41:22">
<BookList total_results="1" page_size="10" page_number="1" shown_results="1">
<BookData book_id="law_and_disorder" isbn="0210406240">
<Title>Law and disorder</Title>
<TitleLong>Law and disorder: law enforcement in television network news</TitleLong>
<AuthorsText>V. M. Mishra</AuthorsText>
<PublisherText publisher_id="asia_pub_house">New York: Asia Pub. House, c1979.</PublisherText>
<Details dewey_decimal="302.2/3"
dewey_decimal_normalized="302.23"
lcc_number="PN4888"
language="eng"
physical_description_text="x, 127 p. ; 22 cm."
edition_info=""
change_time="2004-10-19T23:52:56"
price_time="2005-07-29T02:06:41" />
</BookData>
</BookList>
</ISBNdb>
如何从文件的这一部分获取ISBN号<BookData book_id="law_and_disorder" isbn="0210406240">
?下面是我用来解析的C#:
XmlNodeList nodes = doc.DocumentElement.SelectNodes("/ISBNdb/BookList");
List<Book> books = new List<Book>();
foreach (XmlNode node in nodes)
{
Book book = new Book();
book.author = node.SelectSingleNode("BookData/AuthorsText").InnerText;
book.title = node.SelectSingleNode("BookData/Title").InnerText;
book.ISBN = node.SelectSingleNode("BookData").LastChild.ToString();
books.Add(book);
addInfo(book.author, book.title, book.ISBN);
}
我知道有不同的节点&#39;比如&#39; Title&#39;和&#39;细节&#39;。但是,我不明白如何从节点标签中获取信息。他们自己。任何澄清都非常感激,并且可以根据我的错误定义&#39;
来纠正我谢谢!
答案 0 :(得分:5)
book.ISBN = node.SelectSingleNode("BookData").Attributes["isbn"].Value;
isbn是BookData
和非儿童的属性(即Title
)
答案 1 :(得分:2)
正如所建议的那样,LINQ to XML是一个更好的API。您可以使用XDocument.Parse
或XDocument.Load
解析或加载XML,然后就可以创建图书了:
var books = from bookData in doc.Descendants("BookData")
select new Book
{
author = (string)bookData.Element("AuthorsText"),
title = (string)bookData.Element("Title"),
isbn = (string)bookData.Attribue("isbn")
};
答案 2 :(得分:1)
试试这个:
var detailsNode = node.SelectSingleNode("BookData/Details");
var dewey = detailsNode.Attributes["dewey_decimal"].Value
请注意,在尝试分配其值之前,应使用空值保护来确保该属性存在。
答案 3 :(得分:-2)
这是一个属性,用XML的说法。 http://www.w3.org/TR/xpath/对于&#34;数据模型&#34;可能很方便。分解所有各种各样的部分。知道它的属性然后就可以轻松找到必要的C#...