.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> XML >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Looping through the XML document

Posted By:Karthikeyan Anbarasan       Posted Date: January 09, 2011    Points: 15    Category: XML    URL: http://www.dotnetspark.com  

This code explains on how looping through the XML document
 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Xml;



namespace DemoClass

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}



private void button1_Click(object sender, EventArgs e)

{

XmlDocument document = new XmlDocument();

document.Load("Products.xml");

Textbox1.Text = FormatTextArea(document.DocumentElement as XmlNode, "", "");

}



private string FormatTextArea(XmlNode node, string textMark, string indent)

{

if (node is XmlText)

{

textMark += node.Value;

return textMark;

}



if (string.IsNullOrEmpty(indent))

indent = "";

else

{

textMark += "\r\n" + indent;

}



if (node is XmlComment)

{

textMark += node.OuterXml;

return textMark;

}



textMark += "<" + node.Name;

if (node.Attributes.Count > 0)

{

AddAttributes(node, ref textMark);

}

if (node.HasChildNodes)

{

textMark += ">";

foreach (XmlNode child in node.ChildNodes)

{

textMark = FormatText(child, textMark, indent + " ");

}

if (node.ChildNodes.Count == 1 &&

(node.FirstChild is XmlText || node.FirstChild is XmlComment))

textMark += "";

else

textMark += "\r\n" + indent + "";

}

else

textMark += " />";

return textMark;

}



private void AddAttributes(XmlNode node, ref string textref)

{

foreach (XmlAttribute xaAttr in node.Attributes)

{

textref += " " + xaAttr.Name + "='" + xaAttr.Value + "'";

}

}

}

}

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend