Thursday, July 19, 2007

How to Read/Write xml string in different way using C#.net

How to Read/Write xml string in different way using C#.net

Namespace

using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.IO;
using System.Text;

Example Value

string xmlProduct = "<product><details><code value ="MDI">100</code></details></product>"

Read XML


1) First way you can read string xml using dataset

StringReader productDetails = new StringReader(xmlProduct);
DataSet dsProduct = new DataSet();
dsProduct.ReadXml(productDetails);

2) If you have proper XML format value in file

DataSet dsProduct = new DataSet();
dsProduct.ReadXml("C:\Read.xml");

3) You can use XmlTextReader to read xml

string nodeText; int depth;
//In this way you can convert Xmlstring to memoryStream
byte[] data = Encoding.ASCII.GetBytes(xmlProduct);
MemoryStream memStream = new MemoryStream(data);
XmlTextReader textReader = new XmlTextReader(memStream);
XmlNodeType nodeType;

while (textReader.Read())
{
textReader.MoveToFirstAttribute();
nodeType = textReader.NodeType;
if (nodeType.CompareTo(XmlNodeType.Attribute) == 0)
{
nodeText = textReader.Value;
depth = textReader.Depth;
}
}

4) You can use CmlDocument object to read xml,This is the best way to read xml string to read node by node and all attributes.

XmlDocument xmlProductDoc = new XmlDocument();
xmlProductDoc.LoadXml(xmlProduct);

for (int i = 0; i < xmlProductDoc.GetElementsByTagName("product").Count;i++)
{
string xmlVal = xmlProductDoc.GetElementsByTagName("product").innerXml;
string xmlAttributeVal = xmlProductDoc.GetElementsByTagName("product").
Attributes ["value"].value;
}


Write XML

1) You can use XmlTesWriter to write xml file

XmlTextWriter myXmlTextWriter = new XmlTextWriter("books.xml", null);
myXmlTextWriter.Formatting = Formatting.Indented;
myXmlTextWriter.WriteStartDocument(false);
myXmlTextWriter.WriteDocType("bookstore", null, "books.dtd", null);
myXmlTextWriter.WriteComment("This file represents inventory database");
myXmlTextWriter.WriteStartElement("bookstore");
myXmlTextWriter.WriteStartElement("book", null);
myXmlTextWriter.WriteAttributeString("genre", "autobiography");
myXmlTextWriter.WriteAttributeString("publicationdate", "1990");
myXmlTextWriter.WriteAttributeString("ISBN", "0-4567-123-9");
myXmlTextWriter.WriteElementString("title", null, "Baby book");
myXmlTextWriter.WriteStartElement("Author", null);
myXmlTextWriter.WriteElementString("first-name", "Ritesh");
myXmlTextWriter.WriteElementString("last-name", "Kesharwani");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteElementString("price", "8.9");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteEndElement();
//Write the XML to file and close the myXmlTextWriter
myXmlTextWriter.Flush();
myXmlTextWriter.Close();

2) Basic way to write xml into file

1 comment:

Sarika said...

Good Article , Thanks