Creating a XML Document from scratch without using a file in C#

April 4, 2007 at 2:15 pm 57 comments

One thing that’s annoying is that majority of the XML example assumes that you are loading an XML document from a file, so here’s a simple code example for generating it entirely in memory.

// Create the xml document containe
XmlDocument doc = new XmlDocument();
// Create the XML Declaration, and append it to XML document
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
doc.AppendChild(dec);
// Create the root element
XmlElement root = doc.CreateElement("Library");
doc.AppendChild(root);

// Create Books
// Note that to set the text inside the element,
// you use .InnerText instead of .Value (which will throw an exception).
// You use SetAttribute to set attribute
XmlElement book = doc.CreateElement("Book");
book.SetAttribute("BookType", "Hardcover");
XmlElement title = doc.CreateElement("Title");
title.InnerText = "Door Number Three";
XmlElement author = doc.CreateElement("Author");
author.InnerText = "O'Leary, Patrick";
book.AppendChild(title);
book.AppendChild(author);
root.AppendChild(book);

book = doc.CreateElement("Book");
book.SetAttribute("BookType", "Paperback");
title = doc.CreateElement("Title");
title.InnerText = "Lord of Light";
author = doc.CreateElement("Author");
author.InnerText = "Zelanzy, Roger";
book.AppendChild(title);
book.AppendChild(author);
root.AppendChild(book);

string xmlOutput = doc.OuterXml;

The same code but using an XMLWriter to a memory stream.


XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.Indent = true;
MemoryStream ms = new MemoryStream();
XmlWriter xw = XmlWriter.Create(ms, wSettings);
// Write Declaration
xw.WriteStartDocument();

// Write the root node
xw.WriteStartElement("Library");

// Write the books and the book elements
xw.WriteStartElement("Book");
xw.WriteStartAttribute("BookType");
xw.WriteString("Hardback");
xw.WriteEndAttribute();

xw.WriteStartElement("Title");
xw.WriteString("Door Number Three");
xw.WriteEndElement();
xw.WriteStartElement("Author");
xw.WriteString("O'Leary, Patrick");
xw.WriteEndElement();

xw.WriteEndElement();

// Write another book
xw.WriteStartElement("Book");
xw.WriteStartAttribute("BookType");
xw.WriteString("Paperback");
xw.WriteEndAttribute();

xw.WriteStartElement("Title");
xw.WriteString("Lord of Light");
xw.WriteEndElement();
xw.WriteStartElement("Author");
xw.WriteString("Zelanzy, Roger");
xw.WriteEndElement();

xw.WriteEndElement();

// Close the document
xw.WriteEndDocument();

// Flush the write
xw.Flush();

Byte[] buffer = new Byte[ms.Length];
buffer = ms.ToArray();
string xmlOutput = System.Text.Encoding.UTF8.GetString(buffer);

Advertisements

Entry filed under: .Net.

Installing Ruby on Rail in Puppy My Install Experience with Fedora Core 6

57 Comments Add your own

  • 1. hassib  |  June 20, 2007 at 9:14 pm

    Hi ,

    I am new to C#. When trying the above code as follows:

    XmlWriterSettings wSettings = new XmlWriterSettings();
    wSettings.Indent = true;
    MemoryStream mStream = new MemoryStream();
    XmlWriter writer = XmlWriter.Create(mStream, wSettings);

    writer.WriteStartDocument();
    writer.WriteStartElement(“Ticket”);
    writer.WriteEndElement();
    writer.WriteEndDocument();
    writer.Flush();

    Byte[] buffer = new Byte[mStream.Length];

    buffer = mStream.ToArray();
    string s = System.Text.Encoding.UTF8. GetString(buffer);
    writer.Close();

    Console.WriteLine(s);

    What I am getting is the following:

    ?

    As you can see, I am getting an extra “?” at the beginning of the document.

    Suggestions in why I am getting this extra character? and how to get rid of it?

    Thank you very much in advance

    Reply
  • 2. Stasigr  |  October 29, 2007 at 9:02 am

    Hello, very nice site, keep up good job!
    Admin good, very good.

    Reply
  • 4. Dan  |  February 7, 2008 at 4:52 pm

    Very concise and helpful! Thanks.

    Reply
  • 5. Norm  |  February 20, 2008 at 11:36 am

    hassib – I had a similar problem.

    Turned out I was trying to save a unicode string to a varchar filed in SQL Server. SQL Server didn’t understand the unicode bytes at the start of the string so it turned them into a “?”.

    Fixed it by changing the field to a NVarchar which is designed to handle unicode strings.

    Reply
  • 6. Matthias Meid  |  May 20, 2008 at 7:13 am

    Thank you very much, very helpful. Those XML classes don’t seem like a very straight-forward approach to build simple XML from scratch (at least in my opinion)… 🙂

    Reply
  • 7. marvin  |  July 11, 2008 at 3:12 am

    before I read this.. Great job! you are right about the samples.. most of them just read files…

    this is it. X marks the spot.!

    Reply
  • 8. marvin  |  July 11, 2008 at 3:50 am

    ok after reading it… YES! a good read indeed.. hehehe

    one word

    NEAT!

    Reply
  • 9. nataraj  |  August 20, 2008 at 9:24 am

    This is very useful coding. This is also basic steps to create XML file through coding. simply very good.

    Reply
  • 10. nataraj  |  August 20, 2008 at 9:25 am

    Simply very good. This is basic coding to create XML file through coding.

    Reply
  • 11. TerryG  |  August 21, 2008 at 12:47 pm

    I used this example to achieve an important application objective, as described in the post noted above. I acknowledged The Bonobo Journal (see ‘Code Shavings’). Thanks for the help! Cheers…TCG

    Reply
  • 12. Alok Tripathi  |  November 9, 2008 at 5:45 am

    Very good example…
    i have example of XML Reader and XML Writer , but none of XML Document… You provide me…
    Thanks a lot..
    it provides me comparison wise description.

    Reply
  • 13. Darrell  |  December 1, 2008 at 4:15 pm

    This blog post was great! I searched all over the net but this one helped me immensely Thanks.

    Reply
  • 14. Amol  |  January 27, 2009 at 7:22 pm

    Very Informative article!
    Good Work!

    Reply
  • 15. Alex  |  January 28, 2009 at 6:47 am

    Well done!

    Reply
  • 16. trassebaX  |  May 5, 2009 at 1:17 pm

    emm… really like it )

    Reply
  • 17. Rinku  |  May 11, 2009 at 7:54 am

    Short and nice article.

    Thanks..:)

    Reply
  • 18. Melvin  |  June 6, 2009 at 4:00 am

    I must say… Nice…:)

    Reply
  • 19. Debugger  |  September 2, 2009 at 2:45 am

    Thanks for this sample. Juste a small remark…
    the line ” doc.AppendChild(root); ” should be done after the last ” root.AppendChild(book); “

    Reply
  • 20. Patelos  |  September 2, 2009 at 7:10 am

    I went from not knowing how to generate an XML document to actually completing that part of my development in 10 minutes.

    Thank you.

    Reply
  • 21. Vishal  |  September 24, 2009 at 12:46 am

    Thanks a lot for such a precise, accurate and informative article on XML.

    Reply
  • 23. Shashank  |  January 8, 2010 at 6:33 am

    Really nice and simpe and I agree with you most examples assume that we are using files. Like your post

    thanks again

    Reply
  • 24. Craig  |  February 24, 2010 at 1:43 pm

    This is a nice example. A picture of the output would be helpful as well. thanks.

    Reply
  • 25. Dana  |  March 3, 2010 at 10:52 pm

    To see the created file, add the following line after “string xmlOutput = doc.OuterXml;
    doc.Save(“path to where you want the file saved including a file name“); example: doc.Save(“C:\\documents and settings\\allusers\\nyFirstXML.xml”);. You have to ‘escape’ the ‘escape character’ that is why the double \\ between folders.

    Thank you so much for this example. Unlike so many other tutorials, this worked without any tweaking so the code is good. Using comments to teach rather than a long (possibly boring) written out document is an excellent choice. Let’s face it, if the reader is researching making their own XML, they probably know how to do programming (tutorials tend to talk down to the readers). This was refreshing and educational.

    Reply
    • 26. fastforward2011  |  September 15, 2010 at 11:47 pm

      Thank you very much Dana. I’ve created my XML file successfully. Keep it up. We care, we share.

      Reply
  • 27. Maggie The Dog  |  March 25, 2010 at 8:55 am

    Great work here mate. This has really helped me!

    Reply
  • 28. Karen Avanesyan  |  April 1, 2010 at 9:34 pm

    бесплатное порно фото, видео онлайн большая ежедневно обновляемая база данных самое новое порно видео и фото, фото знаменитостей жесткое порно, девственницы групповое порно.

    бесплатное порно фото, видео онлайн большая база данных самое новое порно видео и фото.

    Reply
  • 29. Raghvandra  |  September 16, 2010 at 2:29 pm

    Thank u so much very help full !!!!!

    Reply
  • 30. Mau  |  October 27, 2010 at 10:02 pm

    Great great way of explaining this… I really apreciatte your effort. I am totally clueless to Xml, but with your kind help, I finished my task in less than 10 minutes.
    Cheers!

    Reply
  • 31. telecominfra  |  November 12, 2010 at 5:50 am

    thanks for this sample code

    Reply
  • 32. steph le plombier  |  February 26, 2011 at 10:45 pm

    how to save the doc to a file?
    thanks for your example.

    Reply
  • 33. Kenny Stas  |  April 7, 2011 at 4:14 am

    Steph, to save the xml to a file add the following code after string xmlOutput = doc.OuterXml;

    doc.Save(“C:\\xmlTest\\Example.xml”);.

    Beware of the double \\ ! This is needed

    Reply
  • 34. Anandhavel  |  May 27, 2011 at 6:27 am

    This is a nice post and it saved my time. Thanks a lot !……..

    Reply
  • 35. test  |  July 13, 2011 at 8:09 am

    Nice Thanks

    Reply
  • 36. supreeth  |  July 14, 2011 at 12:32 am

    good one very simple and informative

    Reply
  • 37. TarasLybin  |  September 25, 2011 at 2:29 pm

    Бесплатно порно видео скачать. Скачать порно видео бесплатно, бесплатное видео порнухи.

    Reply
  • 38. IzjaslavCheljapin  |  September 26, 2011 at 7:41 am

    Мечтаете о новой фигуре – здесь.

    Reply
  • 39. Sharma  |  October 3, 2011 at 12:47 am

    Thanks a lot , very simple and informative

    Reply
  • 40. Amin  |  October 11, 2011 at 8:03 am

    Thank you so much.. great post.

    Reply
  • 41. AskoldGlushkovskij  |  October 15, 2011 at 12:33 pm

    Безопасный порно сайт с трахом. Порно видео сайты онлайн.

    Reply
  • 42. raghav  |  December 5, 2011 at 1:48 am

    Thanks for the example .. its very useful..

    Reply
  • 43. morussxxx  |  January 3, 2012 at 5:11 pm

    http://extube.net/content_preview/ero3/amateur/ricons.jpg
    нажать и смотреть

    скачать прно на мобильный
    скaчaть прно нa мобильный
    прно скачать на мобильный телефон
    скачать прно видео на мобильный
    скачать прно ролики для мобильного
    мобильные прно фильмы скачать
    прно 3gp на мобильный скачать
    прно для мобильного скачать торрент
    скачать прно снятое на мобильный
    скачать прно mp4 на мобильный
    скачать прно в мобильном формате
    скачать прно игры на мобильный
    прно фото для мобильного скачать
    скачать прно на мобильный русское
    скачать прно картинки на мобильный
    скачать частное мобильное прно
    скачать прно на мобильный азиатки
    короткое прно скачать на мобильный
    прно скачать на мобильный онлайн
    скачать гей прно на мобильный
    скачать прно клипы для мобильного
    скaчaть прно нa мобильный
    скaчaть прно нa мобильный
    скaчaть прно нa мобильный
    прно скачать на мобильный телефон
    скачать прно видео на мобильный
    скачать прно ролики для мобильного
    мобильные прно фильмы скачать
    прно для мобильного скачать торрент
    скачать прно снятое на мобильный

    Reply
  • 44. Cezar  |  January 4, 2012 at 6:31 am

    Zelanzy rules! 🙂 Very good article.

    Reply
  • 45. Sergio Ibarra Alcala (@sergio_27)  |  January 13, 2012 at 3:04 pm

    This is awesome. Thank you!

    Reply
  • 46. santosh  |  January 17, 2012 at 4:57 am

    dear friends

    i want to add the validation info in my xml file like this

    how can i do this in my c# code

    Reply
  • 47. vedita  |  March 1, 2012 at 1:33 am

    but how retrive data from this xml file

    Reply
  • 48. Duy  |  March 13, 2012 at 3:44 pm

    I’m trying to get all the PV value in each PMT section. How would I do this using XmlDocument?

    I can get all the PV and all the PMT using
    XmlNodeList PMTList = reader.SelectNodes(“/PARM/PMT”);
    XmlNodeList PVList = reader.SelectNodes(“/PARM/PMT/PV”);

    foreach (XmlNode node in PMTList)
    {
    Console.WriteLine(node.Attributes.GetNamedItem(“NM”).Value);
    }
    foreach (XmlNode node in PVList)
    {
    Console.WriteLine(node.Attributes.GetNamedItem(“PV”).Value);
    }
    but I can’t figure out how to get it per a section. Get all the PVs with the PMT. Blow is an example of what I want and my xml. PLEASE help! Thanks!

    EXAMPLE:
    SOCIETY CODE
    SPE
    OTC
    ARMA

    CONTENT_TYPE
    Conference Paper
    Journal Paper

    0

    Reply
    • 49. Duy  |  March 13, 2012 at 3:45 pm

      The XML Part

      0

      Reply
    • 50. Duy  |  March 13, 2012 at 3:47 pm

      XML part
      please replace # with <

      #PARM#
      #PC#0</PC#
      #PMT NM="SOCIETY_CODE" DN="Publisher" IR="0" T="0"#
      #PV V="SPE" L="" H="" C="444"/#
      #PV V="OTC" L="" H="" C="24"/#
      #PV V="ARMA" L="" H="" C="11"/#
      #PV V="SEG" L="" H="" C="11"/#
      #PV V="IPTC" L="" H="" C="8"/#
      #PV V="NACE" L="" H="" C="1"/#
      #/PMT#
      #PMT NM="CONTENT_TYPE" DN="Content Type" IR="0" T="0"#
      #PV V="Conference Paper" L="" H="" C="468"/#
      #PV V="Journal Paper" L="" H="" C="30"/#
      #PV V="Other" L="" H="" C="1"/#
      #/PMT
      #/PARM#

      Reply
  • 51. Quilpole  |  April 27, 2012 at 11:44 am

    Thanks for the elegant solution. A simple cut/paste operation, a few changes … and it solved my problem immediately 🙂 🙂

    I wish the Microsoft documentation could be so clear.

    … and Zelazny ROCKS!

    Reply
  • 52. Andamon A. Abilar  |  July 16, 2012 at 9:12 pm

    Thank you so much for this article…

    Reply
  • 53. Michael Moreno (@theSemioptimist)  |  July 23, 2012 at 12:17 pm

    Extremely helpful. Thank you!

    Reply
  • 54. mangal deep gupta  |  October 27, 2012 at 2:29 am

    hey this is great and fabulous …

    But i have a problem …

    when i m sending doc to sql server (doc.outerxml) then if there is one row then it is fine otherwise it raise error “Unexepected end of input “”

    wy it is acccured please help me …..

    thank you

    Reply
  • 55. Carla  |  September 23, 2013 at 9:38 pm

    I love your blog.. very nice colors & theme. Did you make this website yourself or did you hire someone to do it for you? Plz reply as I’m looking to create my own blog and would like to find out where u got this from. many thanks

    Reply
  • 56. Jhon  |  May 11, 2014 at 5:41 pm

    using this

    XmlDocument XmlDoc = new XmlDocument();

    XmlNode BigNode = XmlDoc.CreateNode(XmlNodeType.Element, “Shop”, “”);

    XmlDoc.AppendChild(BigNode);

    foreach (Items Object in lstItems)
    {
    XmlNode Temp = Object.CreateObject(XmlDoc);
    BigNode.AppendChild(Temp);
    }
    XmlDoc.Save(“NewXMLDoc.xml”);

    Reply
  • 57. Mixo Mushwana (Mish)  |  February 23, 2015 at 4:22 am

    you should have the output, to aid of explaination

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


Calendar

April 2007
M T W T F S S
« Mar   May »
 1
2345678
9101112131415
16171819202122
23242526272829
30  

Most Recent Posts


%d bloggers like this: