user763554
user763554

Reputation: 2041

How to extract a value from an XML node?

I have a string as follows:

xmlString=@"<product><name>abc</name><price>9.8</price></product>";

I want to extract the value of price and assign it to a variable Price:

double Price = ???

How do I do so given the xmlString?

Upvotes: 0

Views: 3400

Answers (2)

Thit Lwin Oo
Thit Lwin Oo

Reputation: 3438

Try this

string xmlString = @"<product><name>abc</name><price>9.8</price></product>";
XmlDataDocument xmlDoc = new XmlDataDocument();
xmlDoc.LoadXml(xmlString);

XmlNodeList list = xmlDoc.SelectNodes("product/price");

foreach (XmlNode n in list)
  {
     Console.WriteLine(n.ChildNodes[0].Value);
  }

Upvotes: 4

Jeff Mercado
Jeff Mercado

Reputation: 134801

var product = XElement.Parse(xmlString);
var price = (decimal)product.Element("price");

Upvotes: 7

Related Questions