'문서생성'에 해당되는 글 1건

  1. 2007.03.26 XmlDocument를 이용한 XML 문서 작성
posted by 써니루루 2007. 3. 26. 11:07

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;

using System.Xml;
using System.IO;

namespace CH11
{
    class p568_AddNewContent
    {
        static void Main()
        {
            string filePath = @"..\..\booklist.xml";
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(filePath);

            XmlElement eBookList = xDoc.DocumentElement;

            XmlElement eBook = xDoc.CreateElement("book");
            eBook.SetAttribute("id", "b4");
            eBook.SetAttribute("kind", "컴퓨터");
            eBookList.AppendChild(eBook);

            XmlElement eTitle = xDoc.CreateElement("title");
            XmlText txtTitle = xDoc.CreateTextNode("XML Programming .NET");
            eTitle.AppendChild(txtTitle);
            eBook.AppendChild(eTitle);

            XmlElement eAuthor = xDoc.CreateElement("author");
            XmlText txtAuthor = xDoc.CreateTextNode("신민철");
            eAuthor.AppendChild(txtAuthor);
            eBook.AppendChild(eAuthor);

            XmlElement ePublisher = xDoc.CreateElement("publisher");
            XmlText txtPublisher = xDoc.CreateTextNode("프리렉");
            ePublisher.AppendChild(txtPublisher);
            eBook.AppendChild(ePublisher);

            XmlElement ePrice = xDoc.CreateElement("price");
            XmlText txtPrice = xDoc.CreateTextNode("30000");
            ePrice.AppendChild(txtPrice);
            eBook.AppendChild(ePrice);

            StringWriter strWriter = new StringWriter();
            xDoc.Save(strWriter);

            Console.WriteLine(strWriter.ToString());
        }
    }
}



이번 예제는 XML 문서를 XmlDocument로 element들을 생성하고 만들어진 element들을 XmlDocument의 DocumentElement에 AppendChild()를 통해 적용시키는 예제이다.

이러한 방식으로 JavaScript에서도 이용할 수 있다. 어차피 DOM은 여기나 저기나 똑같으니..