잊지 않겠습니다.

'code sample'에 해당되는 글 3건

  1. 2010.01.05 0004. XmlGeneral
  2. 2010.01.05 0002. CSXPath
  3. 2010.01.05 0001. CSXslTransformXml Project

0004. XmlGeneral

Sample Codes 2010.01.05 13:21
xml파일을 각 ElementNode별로 읽고, XmlDocument를 생성하고 저장하는 sample code
XmlDocument에 새로운 Element를 생성하는 것은 생성후에 XmlDocument에 넣는 것이 아니라, XmlDocument를 통해 객체를
생성하고, 생성된 객체에 값을 넣은 이후에 XmlDocument에 Append하는 과정을 거쳐야지 된다는 것을 기억하면 매우 쉬운 소스다.


/****************************** Module Header ******************************\
* Module Name:	Program.cs
* Project:		CSXmlGeneral
* Copyright (c) Microsoft Corporation.
* 
* This C# sample project shows how to read a XML file by using XmlTextReader 
* or XmlNodeReader. It also shows, instead of using forward-only reader, how 
* to read, modify, and update Xml element using the XmlDocument class. This 
* class will load the whole document into memory for modification and we can 
* save the modified XML file to the file system.
* 
* The XML file used by the demo has this format:
* 
* 
*  
*    Gambardella, Matthew
*    XML Developer's Guide
*    Computer
*    44.95
*    2000-10-01
*    
*      An in-depth look at creating applications
*      with XML.
*    
*  
*  
*   ...
*  
* 
* 
* This source is subject to the Microsoft Public License.
* See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
* All other rights reserved.
* 
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
\***************************************************************************/

#region Using directives
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
#endregion


class Program
{
    static void Main(string[] args)
    {
        /////////////////////////////////////////////////////////////////////
        // Read XML document using the XmlTextReader class.
        // 

        // The XmlTextReader acts as a reader pointer that only moves forward.
        // Because it always moves forward and read a piece of data into 
        // memory buffer, it has better performance than the XmlDocument 
        // class which loads the whole document into memory.

        Console.WriteLine("Loading XML using XmlTextReader...");

        XmlTextReader xmlTextReader = new XmlTextReader(@"Books.xml");
        xmlTextReader.WhitespaceHandling = WhitespaceHandling.None;

        while (xmlTextReader.Read())
        {
            if (xmlTextReader.Name == "book")
            {
                Console.WriteLine(xmlTextReader.GetAttribute("id") + ": ");

                xmlTextReader.Read();
                string author = xmlTextReader.ReadElementContentAsString();
                string title = xmlTextReader.ReadElementContentAsString();
                string genre = xmlTextReader.ReadElementContentAsString();
                string price = xmlTextReader.ReadElementContentAsString();
                string publishDate = xmlTextReader.ReadElementContentAsString();
                string description = xmlTextReader.ReadElementContentAsString();

                Console.WriteLine(genre + " book \"" + title + "\" written by \"" +
                    author + "\", published on " + publishDate);
                Console.WriteLine(description);
            }
        }

        xmlTextReader.Close();


        /////////////////////////////////////////////////////////////////////
        // Read XML document using the XmlDocument and XmlNodeReader classes.
        // 

        // XmlNodeReader is similar to XmlTextReader but accepts an XmlNode 
        // instance as target to read. The following code shows how to use 
        // XmlDocument and XmlNodeReader to retrieve XML information. It is 
        // also a forward-only reader.

        Console.WriteLine("Loading XML using XmlDocument & XmlNodeReader...");

        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.Load(@"Books.xml");
        XmlNodeList xmlNodes = xmlDocument.GetElementsByTagName("book");
        foreach (XmlNode node in xmlNodes)
        {
            Console.WriteLine(node.Attributes["id"].Value + ":");

            XmlNodeReader xmlNodeReader = new XmlNodeReader(node);
            xmlNodeReader.Read();
            xmlNodeReader.Read();
            string author = xmlNodeReader.ReadElementContentAsString();
            string title = xmlNodeReader.ReadElementContentAsString();
            string genre = xmlNodeReader.ReadElementContentAsString();
            string price = xmlNodeReader.ReadElementContentAsString();
            string publishDate = xmlNodeReader.ReadElementContentAsString();
            string description = xmlNodeReader.ReadElementContentAsString();

            Console.WriteLine(genre + " book \"" + title + "\" written by \"" +
                author + "\", published on " + publishDate);
            Console.WriteLine(description);
        }


        /////////////////////////////////////////////////////////////////////
        // Make changes to the XmlDocument.
        // 

        // Modify a node value by first calling SelectSingleNode to navigate 
        // to that node and by setting its InnerText property to change its 
        // content.
        XmlNode nodeToModify = xmlDocument.DocumentElement.SelectSingleNode(
            "book/genre");
        nodeToModify.InnerText = "XML Tech";

        // Add a new XML node. In XML programming, we always call 
        // XMLDocument.Create*** to create an attribute or element. After 
        // that, we can add it into where we want by calling Node.AppendChild
        XmlElement newElement = xmlDocument.CreateElement("book");
        XmlAttribute newAttribute = xmlDocument.CreateAttribute("id");
        newAttribute.Value = "bk103";
        XmlElement authorElement = xmlDocument.CreateElement("author");
        authorElement.InnerText = "Mark Russinovich,David Solomon,Alex Ionecsu";
        XmlElement titleElement = xmlDocument.CreateElement("title");
        titleElement.InnerText = "Windows Internals, 5th edition";
        XmlElement genreElement = xmlDocument.CreateElement("genre");
        genreElement.InnerText = "Windows Server 2008";
        XmlElement priceElement = xmlDocument.CreateElement("price");
        priceElement.InnerText = "69.99";
        XmlElement publishDateElement = xmlDocument.CreateElement("publish_date");
        publishDateElement.InnerText = "2009-6-17";
        XmlElement descriptionElement = xmlDocument.CreateElement("description");
        descriptionElement.InnerText = "Windows Internals, 5th edition is the" +
            " update to Windows Internals, 4th edition to cover Windows Vista" +
            " and Windows Server 2008 (32-bit and 64-bit).";

        newElement.Attributes.Append(newAttribute);
        newElement.AppendChild(authorElement);
        newElement.AppendChild(titleElement);
        newElement.AppendChild(genreElement);
        newElement.AppendChild(priceElement);
        newElement.AppendChild(publishDateElement);
        newElement.AppendChild(descriptionElement);
        xmlDocument.DocumentElement.AppendChild(newElement);

        // Save the changes
        xmlDocument.Save("Modified Books.xml");

        // XmlLDocument does not have Close or Dispose method because it is 
        // an in-memory representation of an XML document. Once read, the 
        // file is no-longer needed.
    }
}



  
    Gambardella, Matthew
    XML Developer's Guide
    Computer
    44.95
    2000-10-01
    
      An in-depth look at creating applications
      with XML.
    
  
  
    Ralls, Kim
    Midnight Rain
    Fantasy
    5.95
    2000-12-16
    
      A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.
    
  

저작자 표시 비영리 변경 금지
신고
Posted by xyzlast Y2K

0002. CSXPath

Sample Codes 2010.01.05 13:10
XPathNavigator를 이용해서 Xml 문서를 탐색하고 값을 얻어내는 예제.
특별히 설명될 내용이 없는 간단한 예제이다.

조금 눈 여겨 볼 내용은 XmlDocument를 통해서 생성되는 것이 아닌 XPathDocument를 통해서 XPathNavigator를 생성한다는 점이다.
단순하게 문서를 읽는데에는 XmlDocument나 XDocument를 사용하는 것이 좋으나, xml 파일이 커지거나 xml파일을 일정하게 검색, 변경
할때에는 XPathNavigator를 통해서 검색하는 것이 속도나 코드 면에서 훨씬 좋다.


/****************************** Module Header ******************************\
* Module Name:	Program.cs
* Project:		CSXPath
* Copyright (c) Microsoft Corporation.
* 
* This sample project shows how to use XPathDocument class to load the XML 
* file and manipulate. It includes two main parts, XPathNavigator usage and 
* XPath Expression usage. The first part shows how to use XPathNavigator to 
* navigate through the whole document, read its content. The second part 
* shows how to use XPath expression to filter information and select it out.
* 
* This source is subject to the Microsoft Public License.
* See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
* All other rights reserved.
* 
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
\***************************************************************************/

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


namespace CSXPath
{
    class Program
    {
        static void Main(string[] args)
        {
            #region Initialize XPathDocument and XPathNavigator

            XPathNavigator xPathNavigator;
            XPathDocument xPathDoc;
            
            //Navigate through the whole document
            //Create a new instance of XPathDocument from a XML file
            xPathDoc = new XPathDocument("books.xml");

            //Call CreateNavigator method to create a navigator instance
            //And we will use this navigator object to navigate through whole document
            xPathNavigator = xPathDoc.CreateNavigator();
            
            #endregion

            #region Navigate through the document

            //Move to the root element
            xPathNavigator.MoveToRoot();
            //Catalog element is the first children of the root
            //Move to catalog element
            xPathNavigator.MoveToFirstChild();
            //We can know a XML node's type from the NodeType property
            //XPathNodeType has Attribute, Element, Namespace and so on
            if (xPathNavigator.NodeType == XPathNodeType.Element)
            {
                //We can know if a Node has child nodes by checking its
                //HasChildren property. If it returns true, that node has
                //child nodes
                if (xPathNavigator.HasChildren == true)
                {
                    //Move to the first child which is our first book nodes
                    xPathNavigator.MoveToFirstChild();
                    do
                    {
                        //We can know if a node has any attribute by checking
                        //the HasAttributes property. When this property returns
                        //true, we can get the specified attribute by calling
                        //navigator.GetAttribute() method
                        if (xPathNavigator.HasAttributes == true)
                        {
                            Console.WriteLine("Book ID: " + xPathNavigator.GetAttribute("id", ""));
                        }

                        //Iterate through a book node's child nodes
                        //and list all child node information, like 
                        //name, author, price, publish date and so on
                        if (xPathNavigator.HasChildren)
                        {
                            xPathNavigator.MoveToFirstChild();
                            do
                            {
                                Console.Write("\t{0}:\t{1}\r\n", xPathNavigator.Name, xPathNavigator.Value);
                            } while (xPathNavigator.MoveToNext());
                            //When all child nodes are reached. The MoveToNext() method returns
                            //false. Then we need to call MoveToParent to go back to the book level
                            xPathNavigator.MoveToParent();
                        }
                        //Move to the next book element.
                    } while (xPathNavigator.MoveToNext());
                }
            }

            #endregion

            #region Use of XPath Expression
            
            //Use XPath Expression to select out book bk103
            //The expression should be "/catalog/book[@id='bk103']"
            //@ means to look id attribute and match bk103
            Console.WriteLine("Use XPath Expression to select out the book with ID bk103:");
            XPathExpression expression = xPathNavigator.Compile("/catalog/book[@id='bk103']");
            XPathNodeIterator iterator = xPathNavigator.Select(expression);

            //After compile the XPath expression, we can call navigator.Select
            //to retrieve the XPathNodeIterator. With this interator, we can loop
            //trough the results filtered by the XPath expression
            //The following codes print the book bk103's detailed information
            
            while (iterator.MoveNext())
            {
                XPathNavigator nav = iterator.Current.Clone();
                Console.WriteLine("Book ID: " + nav.GetAttribute("id", ""));
                if (nav.HasChildren)
                {
                    nav.MoveToFirstChild();
                    do
                    {
                        Console.Write("\t{0}:\t{1}\r\n", nav.Name, nav.Value);
                    } while (nav.MoveToNext());
                }
            }


            //Use XPath to select out all books whose price are more than 10.00
            // '[]' means to look into the child node to match the condition "price > 10"
            Console.WriteLine("\r\nUse XPath Expression to select out all books whose price are more than 10:");
            expression = xPathNavigator.Compile("/catalog/book[price>10]");
            iterator = xPathNavigator.Select(expression);

            //After getting the iterator, we print title and price for books 
            //whose price are more than 10
            while (iterator.MoveNext())
            {
                XPathNavigator nav = iterator.Current.Clone();
                Console.WriteLine("Book ID: " + nav.GetAttribute("id", ""));
                if (nav.HasChildren)
                {
                    nav.MoveToFirstChild();
                    do
                    {
                        if (nav.Name == "title")
                        {
                            Console.Write("\t{0}:\t{1}\r\n", nav.Name, nav.Value);
                        }
                        if (nav.Name == "price")
                        {
                            Console.Write("\t{0}:\t{1}\r\n", nav.Name, nav.Value);
                        }
                    } while (nav.MoveToNext());
                }
            }

            //Use XPath Expression to calculate the average price of all books.
            //Here in XPath, we use the sum, div, and count formula.
            Console.WriteLine("\r\nUse XPath Expression to calculate the average price of all books:");
            expression = xPathNavigator.Compile("sum(/catalog/book/price) div count(/catalog/book/price)");
            string averagePrice = xPathNavigator.Evaluate(expression).ToString();
            Console.WriteLine("The average price of the books are {0}", averagePrice);


            #endregion

            #region End. Read a char to exit

            Console.WriteLine("Input any key to quit the sample application");
            Console.ReadLine();

            #endregion
        }
    }
}



  
    Gambardella, Matthew
    XML Developer's Guide
    Computer
    44.95
    2000-10-01
    
      An in-depth look at creating applications
      with XML.
    
  
  
    Ralls, Kim
    Midnight Rain
    Fantasy
    5.95
    2000-12-16
    
      A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.
    
  
  
    Corets, Eva
    Maeve Ascendant
    Fantasy
    5.95
    2000-11-17
    
      After the collapse of a nanotechnology
      society in England, the young survivors lay the
      foundation for a new society.
    
  
  
    Corets, Eva
    Oberon's Legacy
    Fantasy
    5.95
    2001-03-10
    
      In post-apocalypse England, the mysterious
      agent known only as Oberon helps to create a new life
      for the inhabitants of London. Sequel to Maeve
      Ascendant.
    
  
  
    Corets, Eva
    The Sundered Grail
    Fantasy
    5.95
    2001-09-10
    
      The two daughters of Maeve, half-sisters,
      battle one another for control of England. Sequel to
      Oberon's Legacy.
    
  
  
    Randall, Cynthia
    Lover Birds
    Romance
    4.95
    2000-09-02
    
      When Carla meets Paul at an ornithology
      conference, tempers fly as feathers get ruffled.
    
  
  
    Thurman, Paula
    Splish Splash
    Romance
    4.95
    2000-11-02
    
      A deep sea diver finds true love twenty
      thousand leagues beneath the sea.
    
  
  
    Knorr, Stefan
    Creepy Crawlies
    Horror
    4.95
    2000-12-06
    
      An anthology of horror stories about roaches,
      centipedes, scorpions  and other insects.
    
  
  
    Kress, Peter
    Paradox Lost
    Science Fiction
    6.95
    2000-11-02
    
      After an inadvertant trip through a Heisenberg
      Uncertainty Device, James Salway discovers the problems
      of being quantum.
    
  
  
    O'Brien, Tim
    Microsoft .NET: The Programming Bible
    Computer
    36.95
    2000-12-09
    
      Microsoft's .NET initiative is explored in
      detail in this deep programmer's reference.
    
  
  
    O'Brien, Tim
    MSXML3: A Comprehensive Guide
    Computer
    36.95
    2000-12-01
    
      The Microsoft MSXML3 parser is covered in
      detail, with attention to XML DOM interfaces, XSLT processing,
      SAX and more.
    
  
  
    Galos, Mike
    Visual Studio 7: A Comprehensive Guide
    Computer
    49.95
    2001-04-16
    
      Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are
      integrated into a comprehensive development
      environment.
    
  

저작자 표시 비영리 변경 금지
신고
Posted by xyzlast Y2K
CodePlex에서 진행되고 있는 All-In-One Code Framework 소개 (http://cfx.codeplex.com/wikipage?title=All-In-One%20Code%20Framework%20Examples&ProjectName=cfx)

xml파일을 xsl 형식을 이용해서 converting 하는 예제코드.
System.Xml.Xsl.XslCompiledTransform를 이용해서 converting 하는 간단한 예제를 보이고 있다.


 


  
    Gambardella Matthew
    XML Developer's Guide
    Computer
    44.95
    2000-10-01
    An in-depth look at creating applications with XML.
  
  
    Ralls Kim
    Midnight Rain
    Fantasy
    5.95
    2000-12-16
    A former architect battles corporate zombies and her own childhood to become queen of the world.
  
  
    Corets Eva
    Maeve Ascendant
    Fantasy
    5.95
    2000-11-17
    After the collapse of a nanotechnology society in England the young survivors lay the foundation for a new society.
  
  
    Corets Eva
    Oberon's Legacy
    Fantasy
    5.95
    2001-03-10
    In post-apocalypse England the mysterious agent known only as Oberon helps to create a new life for the inhabitants of London. Sequel to Maeve Ascendant.
  
  
    Corets Eva
    The Sundered Grail
    Fantasy
    5.95
    2001-09-10
    The two daughters of Maeve half-sisters battle one another for control of England. Sequel to Oberon's Legacy.
  
  
    Randall Cynthia
    Lover Birds
    Romance
    4.95
    2000-09-02
    When Carla meets Paul at an ornithology conference tempers fly as feathers get ruffled.
  
  
    Thurman Paula
    Splish Splash
    Romance
    4.95
    2000-11-02
    A deep sea diver finds true love twenty thousand leagues beneath the sea.
  
  
    Knorr Stefan
    Creepy Crawlies
    Horror
    4.95
    2000-12-06
    An anthology of horror stories about roaches centipedes scorpions  and other insects.
  
  
    Kress Peter
    Paradox Lost
    Science Fiction
    6.95
    2000-11-02
    After an inadvertant trip through a Heisenberg Uncertainty Device James Salway discovers the problems of being quantum.
  
  
    O'Brien Tim
    Microsoft .NET: The Programming Bible
    Computer
    36.95
    2000-12-09
    Microsoft's .NET initiative is explored in detail in this deep programmer's reference.
  
  
    O'Brien Tim
    MSXML3: A Comprehensive Guide
    Computer
    36.95
    2000-12-01
    The Microsoft MSXML3 parser is covered in detail with attention to XML DOM interfaces XSLT processing SAX and more.
  
  
    Galos Mike
    Visual Studio 7: A Comprehensive Guide
    Computer
    49.95
    2001-04-16
    Microsoft Visual Studio 7 is explored in depth looking at how Visual Basic/Visual C++/C#/ASP+ are integrated into a comprehensive development environment.
  



    
    
      
    
    
      "
      
      "
      
      
        "
        
        "
        
          
        
      
      


    


#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Xsl;
#endregion


namespace CSXslTransformXml
{
    class Program
    {
        static void Main(string[] args)
        {
            XslCompiledTransform transform = new XslCompiledTransform();
            transform.Load("Books.xslt");
            transform.Transform("Books.xml", "Books.csv");
        }
    }
}
저작자 표시 비영리 변경 금지
신고
Posted by xyzlast Y2K


티스토리 툴바