How to get innerXML attribute values using xml reader

13,935

Here's an example:

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

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);
}
Share:
13,935
Relativity
Author by

Relativity

A guy with average IQ - still try to explore microsoft .net day by day :)

Updated on June 15, 2022

Comments

  • Relativity
    Relativity over 1 year

    I have a similar situation as the example here

    How to retrieve the "Price" and "Title" values of a book with given ISBN ?