Monday, June 21, 2010

Loading xml from string

XML Document Approach

Let see how we can load xml from a string to a xmldocument
object
Step 1 Create XmlDocument Object
XmlDocument doc = new
XmlDocument();
Step 2
Creat a StringReader Object
System.IO.StringReader sr = new
System.IO.StringReader("XML
Sring");
Step 3 Create
XmlReader Object
XmlReader xmlrd =
XmlReader.Create(sr)

Here we are calling XmlReader.Create method and passing a
StringReader object
Step 4 Load xml
doc.Load(xmlrd);
Uses Load method of
XmlDocument object and pass XmlReader

XDocument Approach
XDocument.Parse("StringXML", LoadOptions.PreserveWhitespace);
In Xdocument you can directly pass the string and specify the load
options.Even you can directly parse into a XElement
XElement.Parse("StringXML")
You could also specify the declaration for your xml when you are creating the XDocument.Look at the following line
XDocument xdoc = new XDocument(new XDeclaration("1.0", "ISO-8859-1", "YES"), XElement.Parse("StringXML"));

Here XDeclaration you can specify version of xml,encoding you are using and standalone or not

No comments:

Post a Comment