Reading & Writing XML Files
To read
xml files, we can use the XmlReader class. We will use the XML file we created
earlier to assign the values into variables. Note that we will simply use
variables for storing the values from the XML. A better approach is by creating
a Products class the follows the heirarchy of the XML file. The following
program demonstrates the use of XmlReader class.
using
System; using System.Xml; public class Program
{
public
static void Main()
{
XmlReader
reader = XmlReader.Create("Products.xml"); while (reader.Read())
{
if
(reader.NodeType == XmlNodeType.Element && reader.Name ==
"Product")
{
Console.WriteLine("ID
= " + reader.GetAttribute(0)); Console.WriteLine("Name = " +
reader.GetAttribute(1)); while (reader.NodeType != XmlNodeType.EndElement)
{
reader.Read();
if
(reader.Name == "Price")
{
while
(reader.NodeType != XmlNodeType.EndElement)
{
reader.Read();
if
(reader.NodeType == XmlNodeType.Text)
{
Console.WriteLine("Price
= {0:C}", Double.Parse(reader.Value));
}
}
reader.Read();
} //end if
if
(reader.Name == "OtherDetails")
{
while
(reader.NodeType != XmlNodeType.EndElement)
{
reader.Read();
if
(reader.Name == "BrandName")
{
while
(reader.NodeType != XmlNodeType.EndElement)
{
reader.Read();
if
(reader.NodeType == XmlNodeType.Text)
{
Console.WriteLine("Brand
Name = " + reader.Value);
}
}
reader.Read();
} //end if
if
(reader.Name == "Manufacturer")
{
while
(reader.NodeType != XmlNodeType.EndElement)
{
reader.Read();
if
(reader.NodeType == XmlNodeType.Text)
{
Console.WriteLine("Manufacturer
= " + reader.Value);
}
}
} //end
if
}
} //end
if
} //end
while } //end if
} //end
while
}
}
Output:
ID = 001
Name =
Soap
Price =
$10.00
Brand
Name = X Soap
Manufacturer
= X Company
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.