i need to get the value of an Node in an XML File.
My XML file looks like this:
You can use Linq To Xml.
Assuming you you have other products like IPHONE
under PRODUCTS
var products = XDocument.Load(filename).Root
.Elements()
.Select(x => new
{
Product = x.Name.LocalName,
Name = (string)x.Element("NAME"),
Model = (string)x.Element("MODEL"),
Price = (decimal)x.Element("PRICE"),
Color = (string)x.Element("COLOR")
})
.ToList();
I suggest to use Linq to Xml:
var xdoc = XDocument.Load("../XML-Test/Webshop-products.xml");
var p = xdoc.Root.Element("IPHONE"); // get first IPHONE from file
if (iPhoneElement == null)
return; // handle case when there is no IPHONE in xml file
var iPhone = new {
Name = (string)p.Element("NAME"),
Model = (string)p.Element("MODEL"),
Price = (decimal)p.Element("PRICE"),
Color = (string)p.Element("COLOR")
};
Then you can use name, model, price or color of iPhone
object. E.g.
iPhone.Name
Note - if there is many iPhones in file, you can grab them all:
var iPhones = from p in xdoc.Root.Elements("IPHONE")
select new {
Name = (string)p.Element("NAME"),
Model = (string)p.Element("MODEL"),
Price = (decimal)p.Element("PRICE"),
Color = (string)p.Element("COLOR")
};
You may also want to have a look at the methods given below.
1) XmlDocument and XmlNode
2) Serialization and Deserialization.
3) Simplified example of Serialization and Deserialization