I have an xml file that looks like this;

<?xml version="1.0" encoding="utf-8"?>
<!--This file is generated by the program.-->
<Product ID="23" Name="Soap" test="one">
    <BrandName>X Soap</BrandName>
    <Manufacturer>X Company</Manufacturer>

I can use the following code to read the 'ID', 'Name', and 'test;

XmlReader reader = XmlReader.Create("Products.xml");

            while (reader.Read())
                if (reader.NodeType == XmlNodeType.Element && reader.Name == "Product")

My problem is, how can I read the value in the elements like '10.00', 'X Soap', and 'X Company'?

I would use the System.Xml.Linq namespace to reach the elements easier:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace DW_422750_CS_CON
   class Program
      static void Main(string[] args)
         XDocument xd = XDocument.Load("../../XMLFile1.xml");
         //Get just the price

         // Report on all of the elements
         List<XElement> lst_xe = xd.Descendants("Product").ToList();

            from xe in lst_xe
            select new
               PRICE = xe.Element("Price").Value,
               BRAND_NAME = xe.Element("OtherDetails").Element("BrandName").Value,
               MANUFACTURER = xe.Element("OtherDetails").Element("Manufacturer").Value,
         ).ToList().ForEach(x =>
            Console.WriteLine("{0}\t{1}\t{2}", x.PRICE, x.BRAND_NAME, x.MANUFACTURER));


Edited 4 Years Ago by thines01

Hmmm, I was trying that but there is no defintion called Attribute...

This article has been dead for over six months. Start a new discussion instead.