繁体   English   中英

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

[英]How to get innerXML attribute values using xml reader

我和这里的例子有类似的情况

如何使用给定的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对其进行解析:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM