Monday, February 7, 2011

How do I convert XML to string and get the element value?

How do I convert XML to string and get the element value?

Example XML

<Example>
  <Option1>x</Option1>
  <Option2>y</Option2>
  <Option3>z</Option3>
</Example>

.

If i wanted to get

option1 it would return x,

option2 returns y,

option3 returns z.

etc....

  • A simple way to do it:

    using System;
    using System.Xml;
    
    class Test {
        static void Main ()
        {
            string s = "<Example> <Option1>x</Option1> <Option2>y</Option2> <Option3>z</Option3></Example>";
            XmlDocument doc = new XmlDocument (); 
            doc.LoadXml (s);
            XmlNode n = doc.SelectSingleNode ("Example/Option1");
            Console.WriteLine (n.InnerText);
        }
    }
    

    This will print x.

    From Gonzalo
  • You can use Linq on XDocument to query the xml

    From Neowizard

0 comments:

Post a Comment