Wednesday, August 12, 2009

Write the Values to XML element

Creates a XML From Dataset
  1. Populate the DataTable values from Storeproc
  2. Serialize
  3. Write to XMl
  4. Close the writing File

Enter Values to XML

  1. Create a XmlElement as Root
  2. Create a XmlElement below root
  3. Create XmlText which will be the value for XmlElement
  4. Append Child
  5. Save the File

Get the Element Value from XML

  1. Read the XML
  2. Deserilize the object so XML values are now populated to the DataTable
  3. Close the Read
  4. Instantiate xmlDoc
  5. Load it with the XML file
  6. Create a Node
  7. Goto the Node by using GetElementsByTagName("val1")[0];
  8. Get the values of that node by xNode.InnerText


#region Create XML
//Uncomment following lines to create XML

int val1 =1; // Initialize to an appropriate value
expected = className.FuncReturnsStoreProc(val1);
////Serialization
XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(expected.GetType());
TextWriter tw=new StreamWriter(strFilename);
xs.Serialize(tw, expected);
tw.Close();

////Create Input values to the XML Element

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(strFilename);
if (File.Exists(strFilename))
{

XmlElement elmRoot = xmlDoc.DocumentElement;
elmRoot = xmlDoc.DocumentElement;

XmlElement elmVal = xmlDoc.CreateElement("val1");
XmlText valToXML = xmlDoc.CreateTextNode(val1.ToString());
elmRoot.AppendChild(elmVal);
elmRoot.LastChild.AppendChild(valToXML);

xmlDoc.Save(strFilename);
}

//Uncomment ends
#endregion

#region Get XML data

//Deserialization
XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(expected.GetType());
TextReader tr = new StreamReader(strFilename);
expected = (ObjectName)xs.Deserialize(tr); //Convert to the ObjectName
tr.Close();

//////Reads Input parameter and pass it to the actual
int val1; // Gets the Input parameter value from XML
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(strFilename);
XmlNode xNode;
xNode = xmlDoc.GetElementsByTagName("val1")[0];
val1 = Convert.ToInt32(xNode.InnerText);

#endregion


Thanks :http://www.functionx.com/csharp/xml/Lesson03.htm

No comments:

Post a Comment