C#: Simple way to parse XML string to get Value from the tag

person Jason Huangfolder_openC#, Codelocal_offer, , access_time April 6, 2016

C# makes it very easy to parse a xml file or string.

For example, if you want to parse the following xml file, looking just for the value of the tag called “score”:


<?xml version=”1.0″ encoding=”UTF-8″?>
<results>
<status>OK</status>
<url>http://www.monkeycancode.com/</url>
<totalTransactions>1</totalTransactions>
<language>english</language>
<mixed>1</mixed>
<score>0.111642</score>
<type>positive</type>
</results>


This will work even with tag element that is in a nested tag.

        private string ParseResultXML(string sXML, string Tag)
        {
            string sOutput = "";
 
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.LoadXml(sXML);
            XmlNodeList nodeList = xmldoc.GetElementsByTagName(Tag);
 
            foreach (XmlNode aNode in nodeList)
            {
                sOutput = aNode.InnerText;
            }
 
            return sOutput;            
        }

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>