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. 26. 10:44

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

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE booklist SYSTEM "booklist.dtd">

<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>


Javascript에서 DOM을 이용해본 사람이라면 익숙할 getElementById() 메소드를 이용하는 동일한 사용법으로 이용할 수 있다.

ID를 이용해서 테그를 선택해야하는데. 단, HTML DOM은 이미 ID라는 attribute가 정의 되어 있지만 xml에서는 id attribute가 정해져 있는 것이 아니다.

따라서 위 xml파일과 같이 dtd 파일에서 attribute를 ID특성으로 정의 해줘야 한다.

참조하는 DTD 파일은 다음과 같다. 'booklist.dtd'

<?xml version="1.0" encoding="utf-8" ?>
<!ELEMENT booklist (book*)>
<!ELEMENT book (title,author,publisher,price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT publisher (#PCDATA)>
<!ELEMENT price (#PCDATA)>

<!ATTLIST book
  id  ID  #REQUIRED
  kind  CDATA #IMPLIED>


이를 이용한 C# 코드는 다음과 같다.

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

using System.Xml;

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

            XmlElement element = xDoc.GetElementById("b2");

            string title = element.FirstChild.FirstChild.Value;
            Console.WriteLine(title);
        }
    }
}


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

posted by 써니루루 2007. 3. 26. 10:29
읽어들일 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>


이번 예제는 Javascript 로 dom을 이용한 분들은 친숙할 getElementByTagName() 메소드를 보게되는 예제이다. 마찬가지로 tag 이름을 가지고 엘리먼트를 선택하는 예제이다.

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

using System.Xml;

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

            XmlNodeList titleNodeList = xDoc.GetElementsByTagName("title");
            for (int i = 0; i < titleNodeList.Count; i++)
            {
                XmlNode titleNode = titleNodeList[i];
                XmlNodeList childNodeList = titleNode.ChildNodes;
                XmlNode textNode = childNodeList[0];
                string value = textNode.Value;
                Console.WriteLine(value);
            }
        }
    }
}

title 엘리먼트를 찾고 책의 제목을 출력하게되는 예제이다.

posted by 써니루루 2007. 3. 26. 10:21
읽어들일 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>


이번 예제는 XmlAttributeCollection을 이용해 element에 속한 attribute를 collection으로 가져와서 loop를 이용해 출력하는 예제를보여준다.

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

using System.Xml;

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

            XmlElement eBook = xDoc.DocumentElement;
            XmlElement eFirstBook = (XmlElement)eBook.FirstChild;

            XmlAttributeCollection attributes = eFirstBook.Attributes;

            // loop를 이용한 attribute 탐색
            for (int i = 0; i < attributes.Count; i++)
            {
                XmlAttribute attribute = (XmlAttribute)attributes[i];
                Console.WriteLine(attribute.Name + "\t" + attribute.Value);
            }

            // 직접 attribute 출력
            string id = eFirstBook.GetAttribute("id");
            Console.WriteLine("id:\t" + id);

            string kind = eFirstBook.GetAttribute("kind");
            Console.WriteLine("kind:\t" + kind);
        }
    }
}

attribute를 탐색할때 위 예제와 같이 활용하면 되겠다.

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

posted by 써니루루 2007. 3. 26. 10:01
읽어들일 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>


이번 예제는 NextSibling, PreviousSibling을 이용해서 Element의 앞, 뒤 노드를 탐색하는 예제입니다.

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

using System.Xml;

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

            XmlElement eBook = xDoc.DocumentElement;
            XmlElement eFirstBook = (XmlElement)eBook.FirstChild;
            XmlElement eNextBook = (XmlElement)eFirstBook.NextSibling;

            XmlElement eLastBook = (XmlElement)eBook.LastChild;
            XmlElement ePreviousBook = (XmlElement)eLastBook.PreviousSibling;

            if (eNextBook == ePreviousBook)
            {
                Console.WriteLine("동일한 Book 엘리먼트 입니다.");
            }
            else
            {
                Console.WriteLine("다른 Book 엘리먼트 입니다.");
            }
        }
    }
}



위 원본 XML 파일에 book 노드가 4개이고,
첫노드의 다음 노드는 b2 book이고, 마지막노드의 이전 노드는 b3 book이 된다.
따라서 두개의 book 엘리먼트는 다른 엘리먼트가 된다.

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

posted by 써니루루 2007. 3. 26. 09:52
읽어들일 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>



위 문서를 C#으로 읽어 들이기 위해 XmlDocument 개체를 이용한다.


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

using System.Xml;

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

            XmlElement eBook = xDoc.DocumentElement;
            XmlElement eFirstBook = (XmlElement)eBook.FirstChild;
            XmlNodeList nlChilds = eFirstBook.ChildNodes;

            for (int i = 0; i < nlChilds.Count; i++)
            {
                XmlElement eChild = (XmlElement)nlChilds[i];
                Console.WriteLine(eChild.Name + ":" + eChild.InnerText);
            }
        }
    }
}


XmlElement를 읽어 들인후 그 하위 노드의 리스트를 생성해서 for문을 이용해 loop를 돌리는 예제이다.

각각의 루프에서는 하위 자식노드의 갯수를 세서 그만큼의 자식 element를 생성하고 그 노드들을 제어한다.

위에보면 Javascript 등에서도 자주 봤던 .InnerText 가 눈에 띈다..

 

posted by 써니루루 2007. 3. 26. 09:42
읽어들일 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>



위 문서를 C#으로 읽어 들이기 위해 XmlDocument 개체를 이용한다.

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

using System.Xml;

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

            XmlElement eBook = xDoc.DocumentElement;

            XmlElement eFirstBook = (XmlElement)eBook.FirstChild;
            XmlElement eLastBook = (XmlElement)eBook.LastChild;

            Console.Write("첫 번째 책 정보 : ");
            Console.WriteLine("\t" + "id=" + eFirstBook.GetAttribute("id"));

            Console.Write("마지막 책 정보 : ");
            Console.WriteLine("\t" + "id=" + eLastBook.GetAttribute("id"));
        }
    }
}




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

posted by 권오성의 Biomedical Engineering 2007. 3. 23. 15:25

XmlReader 클래스는 W3C XML(Extensible Markup Language) 1.0 및 Namespaces in XML 권장 사항을 준수합니다.

현재 노드란 판독기가 배치된 노드를 말합니다. 판독기는 읽기 메서드를 사용해 앞으로 이동하며, 속성은 현재 노드의 값을 반영합니다.

XmlReader는 XML 구문 분석 오류에 대해 XmlException을 throw합니다. 예외가 throw되면 판독기 상태는 예측할 수 없습니다. 예를 들어, 보고된 노드 형식은 현재 노드의 실제 노드 형식과 다를 수 있습니다. ReadState 속성을 사용하여 판독기에 오류가 있는지 확인합니다.

중요:

Microsoft .NET Framework에는 XmlReader 클래스에서 구현된 XmlTextReader, XmlNodeReaderXmlValidatingReader 클래스 등이 있지만 2.0 릴리스에서는 Create 메서드를 사용하여 XmlReader 인스턴스를 만드는 방법이 권장됩니다. 자세한 내용은 XML 판독기 만들기를 참조하십시오.




XmlWriter
클래스는 W3C XML(Extensible Markup Language) 1.0 및 Namespaces in XML 권장 사항을 지원합니다.

* 참고

Microsoft .NET Framework에는 XmlWriter 클래스에서 구현된 XmlTextWriter 클래스가 포함되어 있지만 2.0 릴리스에서는 Create 메서드를 사용하여 새 XmlWriter 개체를 만드는 방법이 권장됩니다. Create 메서드를 사용하면 새로 만든 XmlWriter 개체에서 지원할 기능을 지정할 수 있을 뿐만 아니라 2.0 릴리스에 도입된 새 기능을 충분히 활용할 수 있습니다.



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]