An ASP.net (written in C#) example below will show How to read item name and item value of each element in a XML string. In order to keep it simple, the XML string just contains 2 elements with text inside a CDATA section and have one attribute.
The asp.net example below will use XmlDocument to load the XML string so we need to use System.Xml namespace.
C# read item name, value and attribute from XML string
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Xml; public partial class parse_item_value_from_xml_string : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string xml = ""; xml += "<xml>"; xml += "<first_name title='Mr'><![CDATA[Hoan]]></first_name>"; xml += "<last_name><![CDATA[Huynh]]></last_name>"; xml += "<website>http://4rapiddev.com</website>"; xml += "<role>Admin</role>"; xml += "<first_name title='Ms'><![CDATA[Chau]]></first_name>"; xml += "<last_name><![CDATA[Nguyen]]></last_name>"; xml += "<website>http://4rapiddev.com</website>"; xml += "<role>Editor</role>"; xml += "</xml>"; XmlDocument dom = new XmlDocument(); dom.LoadXml(xml); XmlNodeList root = dom.DocumentElement.ChildNodes; for (int i = 0; i < root.Count; i++) { XmlAttributeCollection attr = root.Item(i).Attributes; for (int j = 0; j < attr.Count; j++) { Response.Write(attr.Item(j).Name + ": " + attr.Item(j).InnerText + "<br>"); } Response.Write(root.Item(i).Name + ": " + root.Item(i).InnerText + "<br>"); } } } |
Output
title: Mr first_name: Hoan last_name: Huynh website: http://4rapiddev.com role: Admin title: Ms first_name: Chau last_name: Nguyen website: http://4rapiddev.com role: Editor |