posted by 써니루루 2007. 7. 8. 23:10
http://www.ibm.com/developerworks/kr/library/wa-ajaxintro5/

Ajax를 이용해 받아온 데이터를 DOM으로 제어하는 경우가 많습니다.

기본적인 사항을 위 페이지에서 보실 수 있습니다.
posted by 써니루루 2007. 3. 26. 12:46

약간은 어려운 내용일 수 있다.
XmlDocument로는 문서와 Dataset과의 동기화가 되지 않아 XmlDataDocument를 이용하게된다.

아래는 이러한 내용을 보여주는 예제이다.


using System;
using System.Data;
using System.Data.SqlClient;
using System.Xml;

namespace XmlDataDocumentUpdate
{
    public class Class1
    {
        static void Main(string[] args)
        {
            //DataAdapter 객체 생성
            string strConn = "Data Source=localhost;Initial Catalog=booksourcedb;Integrated Security=True";
            string strSql = "SELECT * FROM book";
            SqlDataAdapter dataAdapter = new SqlDataAdapter(strSql, strConn);
            SqlCommandBuilder builder = new SqlCommandBuilder(dataAdapter);

            //데이터베이스에서 데이터 가져오기
            DataSet dataSet = new DataSet("booklist");
            dataAdapter.Fill(dataSet, "book");

            //XmlDataDocument 객체 생성
            XmlDataDocument xdd = new XmlDataDocument(dataSet);

            //XPath로 수정을 할 책 찾기
            string xpath = "/booklist/book[bid='b2']";
            XmlElement eBook = (XmlElement)xdd.SelectSingleNode(xpath);

            //책 가격을 수정
            XmlElement ePrice = (XmlElement)eBook.ChildNodes[4];
            dataSet.EnforceConstraints = false;
            ePrice.InnerText = Convert.ToString(12000);
            dataSet.EnforceConstraints = true;

            //변경된 DataSet 내용 보여주기
            DataTable dataTable = dataSet.Tables["book"];
            dataTable.PrimaryKey = new DataColumn[] { dataTable.Columns["bid"] };
            DataRow dataRow = dataTable.Rows.Find("b2");
            Console.WriteLine("원래 책 가격: " + dataRow["price", DataRowVersion.Original]);
            Console.WriteLine("수정 책 가격: " + dataRow["price"]);

            //데이터베이스에 업데이트
            dataAdapter.Update(dataSet, "book");
        }
    }
}



Ref. .NET 개발자를 위한 XML p.615
posted by 써니루루 2007. 3. 26. 12:13

XML Data를 윈폼의 DataGridView 컨트롤에 바인딩 시켜준다.


위 예제는 윈폼예제여서 소스를 압축해서 올렸다.

코드부분은 Form Load 부분만 추린 아래 예제코드를 보도록 하자.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace CH13
{
    public partial class ReadXmlForGridView : Form
    {
        public ReadXmlForGridView()
        {
            InitializeComponent();
        }

        private void ReadXmlForGridView_Load(object sender, EventArgs e)
        {
            DataSet dataSet = new DataSet();
            dataSet.ReadXml(@"..\..\booklist.xml");

            BindingSource bindingSource = new BindingSource();
            bindingSource.DataSource = dataSet.Tables[0];
            dataGridView1.DataSource = bindingSource;
        }
    }
}


Ref. .NET 개발자를 위한 XML p.605

 

posted by 써니루루 2007. 3. 26. 11:58

앞전에 포스팅한 내용은 데이터를 가져오는 것이고.

이번 예제에서는 내용을 파일로 저장하는 방법을 보게 된다.

using System;
using System.Data;
using System.Data.SqlClient;

namespace booksource.ch13
{
  class WriteXmlAndSchema
  {
    static void Main()
    {
      string strConn = "Data Source=localhost;Initial Catalog=booksourcedb;Integrated Security=True";
      string strSql = "SELECT * FROM book";
      SqlDataAdapter dataAdapter = new SqlDataAdapter(strSql, strConn);

      DataSet dataSet = new DataSet("booklist");
      dataAdapter.Fill(dataSet, "book");

      dataSet.WriteXml(@"C:\Temp\booklist.xml");
      dataSet.WriteXmlSchema(@"C:\Temp\booklist.xsd");
    }
  }
}




 Ref. .NET개발자를 위한 XML

posted by 써니루루 2007. 3. 26. 11:56

dataset에서 GetXml()이나 GetXmlSchema() 메소드를 이용한다.


위 SQL 파일을 DB 에서 실행해서 해당 Database를 만들어야 예제를 실행할 수 있다.

아래 예제코드는 위에서 입력된 자료를 이용해서 XML로 가져오는 예제코드이다.

using System;
using System.Data;
using System.Data.SqlClient;

namespace CH13
{
    class GetXmlAndSchema
    {
        static void Main()
        {
            string strConn = "Data Source=localhost;Initial Catalog=booksourcedb;Integrated Security=True";
            string strSql = "SELECT * FROM book";
            SqlDataAdapter dataAdapter = new SqlDataAdapter(strSql, strConn);

            DataSet dataSet = new DataSet("booklist");
            dataAdapter.Fill(dataSet, "book");

            string strXml = dataSet.GetXml();
            string strSchema = dataSet.GetXmlSchema();

            Console.WriteLine("[DataSet 내용을 XML 문서로 쓰기]");
            Console.WriteLine("------------------------------------");
            Console.WriteLine(strXml);

            Console.WriteLine("\n[DataSet 구조를 Schema 문서로 쓰기]");
            Console.WriteLine("------------------------------------");
            Console.WriteLine(strSchema);
        }
    }
}


Ref. .NET 개발자를 위한 XML p.600

posted by 써니루루 2007. 3. 26. 11:40

invalid-file

예제코드

XSLT를 이용해서 문서를 변환하는 예제를 보여준다.

using System;
using System.Xml;
using System.Xml.Xsl;
using System.Diagnostics;

namespace booksource.ch12
{
  class Transformation
 {
  static void Main()
  {
      //XSLT 문서 지정
      string xslFilePath = @"..\..\ch12\booklist.xsl";
      XslCompiledTransform transformer = new XslCompiledTransform();
      transformer.Load(xslFilePath);
   
      //원본 XML 문서 지정
      string xmlFilePath = @"..\..\ch12\booklist.xml";
      XmlReader xmlReader = XmlReader.Create(xmlFilePath);
     
      //출력 형태 지정
      string resultFilePath = @"C:\Temp\result.htm";
      XmlWriter xmlWriter = XmlWriter.Create(resultFilePath);

      //변환하기
      transformer.Transform(xmlReader, xmlWriter);

      //인터넷 익스플로러 실행
      Process.Start("IExplore.exe", @"C:\Temp\result.htm");
  }
 }
}




Ref. .NET 개발자를 위한 XML p.581

posted by 써니루루 2007. 3. 26. 11:32


XML 문서를 XmlDocument를 이용해 생성한다.
기본으로 유니코드로 저장하기 때문에 한글이 깨지는 문제가 발생하는데, 이 때문에 이 방법 보다는 XmlWriter를 이용해서 XmlWriter.create를 이용해 문서를 생성하는 방법이 더 나은것 같다.

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

using System.Xml;

namespace CH11
{
    class p575_NewDOM
    {
        static void Main()
        {
            XmlDocument xDoc = new XmlDocument();

            XmlElement eBookList = xDoc.CreateElement("booklist");
            xDoc.AppendChild(eBookList);

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

            eTitle.AppendChild(txtTitle);
            eBook.AppendChild(eTitle);

            eBook.SetAttribute("id", "b10");
            eBook.SetAttribute("kind", "컴퓨터");
            eBookList.AppendChild(eBook);

            xDoc.Save(@"..\..\booklist2.xml");
        }
    }
}

ref. .NET 개발자를 XML p.575

posted by 써니루루 2007. 3. 26. 11:21

이번 예제에서는 Element, Attribute를 DOM을 이용해 삭제하는 방법을 다룬다.

(읽어들일 XML문서는 이전에 포스팅한 글을 참조한다)

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

using System.Xml;
using System.IO;

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

            XmlElement eBookList = xDoc.DocumentElement;

            XmlNodeList nlBooks = xDoc.GetElementsByTagName("book");
            foreach (XmlElement eBook in nlBooks)
            {
                eBook.RemoveAttribute("kind");
            }

            XmlElement eLastBook = (XmlElement)eBookList.LastChild;
            eBookList.RemoveChild(eLastBook);

            StringWriter strWriter = new StringWriter();
            xDoc.Save(strWriter);
            Console.WriteLine(strWriter.ToString());
        }
    }
}


Ref. .NET 닷넷 개발자를 위한 XML p.574

posted by 써니루루 2007. 3. 26. 11:14

(불러들이는 XML 파일은 이전에 포스트한 글을 참조한다)

이 글에서는 Xml 문서를 읽어들여 값을 수정하는 예제를 보여준다.
.InnerText와 SetAttribute()를 보도록 하자.

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 eFirstBook = (XmlElement)eBookList.FirstChild;
            XmlElement eTitle = (XmlElement)eFirstBook.ChildNodes[0];
            eTitle.InnerText = ".NET 개발자를 위한 XML";
            eFirstBook.SetAttribute("kind", "프로그래밍 언어");

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

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

Ref. .NET 닷넷 개발자를 위한 XML p.570
 

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은 여기나 저기나 똑같으니..