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. 10:57

사용한 XML 문서는 이전 글을 참조하기 바란다.


 

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

using System.Xml.XPath;

namespace CH11
{
    class p566_XPathNavagator
    {
        static void Main()
        {
            string filePath = @"..\..\booklist.xml";
            XPathDocument xPathDoc = new XPathDocument(filePath);
            XPathNavigator xPathNavi = xPathDoc.CreateNavigator();

            // XPath 반복기
            XPathNodeIterator xPathNodeIterator = xPathNavi.Select(
                "//booklist/book/title[../@kind='컴퓨터']");

            while (xPathNodeIterator.MoveNext())
            {
                XPathNavigator naviTitle = xPathNodeIterator.Current;
                Console.WriteLine(naviTitle.Value);
            }
        }
    }
}

posted by 써니루루 2007. 3. 26. 10:50

읽어들일 XML 파일 'booklist.xml'

<?xml version="1.0" encoding="utf-8" ?>
<booklist>
  <book id="b1" kind="컴퓨터">
    <title>기초에서 실무까지 XML</title>
    <author>신민철</author>
    <publisher>프리렉</publisher>
    <price>35000</price>
  </book>
 
  <book id="b2" kind="소설">
    <title>사랑과 전쟁</title>
    <author>이사랑</author>
    <publisher>전쟁문화사</publisher>
    <price>15000</price>
  </book>
 
  <book id="b3" kind="잡지">
    <title>마이크로 소프트</title>
    <author>빌 게이츠</author>
    <publisher>마소문화사</publisher>
    <price>20000</price>
  </book>
 
  <book id="b4" kind="소설">
    <title>액션가면부인 바람났네</title>
    <author>짱구</author>
    <publisher>짱구출판사</publisher>
    <price>12000</price>
  </book>
</booklist>


Xml Node를 XPath를 이용해서 선택하는 예제이다.

예제에서는 kind가 '컴퓨터'인 node를 선택하는 예제코드를 보여준다.



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

using System.Xml;

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

            string xPath = "//booklist/book/title[../@kind='컴퓨터']";
            XmlNodeList nodeList = xDoc.SelectNodes(xPath);

            for (int i = 0; i < nodeList.Count; i++)
            {
                string title = nodeList[i].InnerText;
                Console.WriteLine(title);
            }
        }
    }
}


ref. .NET 닷넷 개발자를 위한 XML p.564

posted by 써니루루 2007. 3. 22. 12:05
URL Reference : http://blog.jusun.org/tt/entry/XPath-expression(새 창으로 열기)


XPath란 무엇인가?
  • XPath는 XML 문서의 part를 정의하기 위한 syntax이다.
  • XPath는 XML 문서 내부를 검색하기 위한 path expression을 사용한다.
  • XPath는 표준함수의 라이브러리를 갖고 있다.
  • XPath는 W3C 표준이다.
Xpath의 노드
  • Xpath에는 7가지 종류의 Node가 존재한다.
  • element, attribute, text, namespace, processing-instruction,
  • comment, document(root)
Node간의 관계
  • parent, children, sibling, ancestor, descendant
Xpath Syntax
  • Xpath는 Xml 문서내에서 노드와 노드셋을 선택하기 위해 path expression을 사용한다.
  • 노드는 path 또는 step에 의해 선택된다.





Xpath Axis
Xpath는 Axis는 현재 노드와 노드셋과의 관계를 정의 한다.



Axis(축) 표현
Axisname::nodeset[predicate]