如何使用xml阅读器获取innerXML属性值

本文关键字:获取 innerXML 属性 何使用 xml | 更新日期: 2023-09-27 18:27:22

我的情况与这里的示例类似

如何检索给定ISBN的图书的"价格"answers"标题"值?

如何使用xml阅读器获取innerXML属性值

这里有一个例子:

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对其进行解析:

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);
}