如何使用xml阅读器获取innerXML属性值 [英] How to get innerXML attribute values using xml reader
本文介绍了如何使用xml阅读器获取innerXML属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有与示例类似的情况此处
如何检索具有给定 ISBN 的图书的价格"和标题"值?
How to retrieve the "Price" and "Title" values of a book with given ISBN ?
推荐答案
举个例子:
class Program
{
static void Main()
{
var xml =
@"
<bookstore>
<book genre='novel' ISBN='10-861003-324'>
<title>The Handmaid's Tale</title>
<price>19.95</price>
</book>
<book genre='novel' ISBN='1-861001-57-5'>
<title>Pride And Prejudice</title>
<price>24.95</price>
</book>
</bookstore>
";
using (var reader = new StringReader(xml))
using (var xmlReader = XmlReader.Create(reader))
{
var bookFound = false;
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == "book")
{
var isbn = xmlReader.GetAttribute("ISBN");
bookFound = isbn == "1-861001-57-5";
}
if (bookFound && xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == "title")
{
Console.WriteLine("title: {0}", xmlReader.ReadElementContentAsString());
}
if (bookFound && xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == "price")
{
Console.WriteLine("price: {0}", xmlReader.ReadElementContentAsString());
}
}
}
}
}
如果您正在阅读的 XML 文件不是很大并且可以放入内存,您可以使用 XDocument 来解析它:
and if the XML file that you are reading is not very big and can fit into memory you could use an XDocument to parse it:
var doc = XDocument.Parse(xml);
var result =
(from book in doc.Descendants("book")
where book.Attribute("ISBN").Value == "1-861001-57-5"
select new
{
Title = book.Element("title").Value,
Price = book.Element("price").Value
}).FirstOrDefault();
if (result != null)
{
Console.WriteLine("title: {0}, price: {1}", result.Title, result.Price);
}
这篇关于如何使用xml阅读器获取innerXML属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文