잊지 않겠습니다.

NHibernate에서 상속된 model을 지원하는 방법은 총 3가지가 있다.

1. "subclass" 로 하나의 Table에 discriminator column을 지정해서 생성하는 방법
  - discriminator 값으로는 class의 full name이 들어가게 된다.
2. "joined-subclass"로 model의 parent class를 하나의 Table로, 그리고 나머지 model의 property를 묶은 table을 FK로 엮는 방법
3. "union-subclass"로 정규화를 고려하지 않고, 상속된 모든 property를 각각의 table로 구현하는 방법


subclass


01.<!--?xml version="1.0" encoding="utf-8" ?-->
02.<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHibernate.First" namespace="NHibernate.First.Models">
03.  <class name="Product">
04.    <id name="Id">
05.      <generator class="guid.comb"></generator>
06.    </id>
07.    <discriminator column="ProductType"></discriminator>   
08.    <property name="Name"></property>   
09.    <property name="Description"></property>
10.    <property name="UnitPrice" not-null="true" type="Currency"></property>
11.  </class>
12.  <subclass name="Book" extends="Product">
13.    <property name="Author"></property>
14.    <property name="ISBN"></property>
15.  </subclass
16.  <subclass name="Movie" extends="Product">
17.    <property name="Director"></property>
18.  </subclass>
19.</hibernate-mapping>


joined-subclass


01.<!--?xml version="1.0" encoding="utf-8" ?-->
02.<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHibernate.First" namespace="NHibernate.First.Models">
03.  <class name="Product">
04.    <id name="Id">
05.      <generator class="guid.comb"></generator>
06.    </id>
07.    <property name="Name"></property>   
08.    <property name="Description"></property>
09.    <property name="UnitPrice" not-null="true" type="Currency"></property>
10.  </class>
11.  <joined-subclass name="Book" extends="Product">
12.    <key column="Id"></key>
13.    <property name="Author"></property>
14.    <property name="ISBN"></property>
15.  </joined-subclass>
16.  <joined-subclass name="Movie" extends="Product">
17.    <key column="Id"></key>
18.    <property name="Director"></property>   
19.  </joined-subclass>
20.</hibernate-mapping>

union-subclass


01.<!--?xml version="1.0" encoding="utf-8" ?-->
02.<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHibernate.First" namespace="NHibernate.First.Models">
03.  <class name="Product">
04.    <id name="Id">
05.      <generator class="guid.comb"></generator>
06.    </id>
07.    <property name="Name"></property>   
08.    <property name="Description"></property>
09.    <property name="UnitPrice" not-null="true" type="Currency"></property>
10.  </class>
11.  <union-subclass name="Book" extends="Product">   
12.    <property name="Author"></property>
13.    <property name="ISBN"></property>
14.  </union-subclass>
15.  <union-subclass name="Movie" extends="Product">
16.    <property name="Director"></property>   
17.  </union-subclass>
18.</hibernate-mapping>

Posted by Y2K
,
RSAServiceProvider를 이용해서 xml 파일에 서명 및 Decryption 하는 과정
RSAServiceProvider를 제공된 public key를 이용해서 얻어내는 것이 이 코드의 핵심.



001.private String publicOnlyKey;
002.private void btnSign_Click(object sender, EventArgs e)
003.{
004.    try
005.    {
006.        /////////////////////////////////////////////////////////////////
007.        // Create a new RSA signing key and export public key for
008.        // verification.
009.         
010.        RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider();
011.         
012.        //Public Key exported
013.        //Public Key 뿐 아니라 Private Key도 얻어내는 것이 가능하다. 사용자에게 Key를 보내거나 저장할 때 이용 가능
014.        publicOnlyKey = rsaKey.ToXmlString(false);
015.        tbxRSAParameters.Text = publicOnlyKey;
016.         
017.        /////////////////////////////////////////////////////////////////
018.        // Sign the XML document.
019.        //
020. 
021.        SignXml(xmlDoc, rsaKey);
022.        MessageBox.Show("XML file signed.");
023. 
024. 
025.        /////////////////////////////////////////////////////////////////
026.        // Save and display the signed document.
027.        //
028. 
029.        xmlDoc.Save("test1.xml");
030.        tbxDigitalSignature.Text = xmlDoc.OuterXml;
031.    }
032.    catch (Exception ex)
033.    {
034.        Console.WriteLine(ex.Message);
035.    }
036.}
037. 
038.///XML파일을 RSA를 이용해서 서명. SignedXml class가 있는 것을 기억하고 있을것!
039.public static void SignXml(XmlDocument Doc, RSA Key)
040.{
041.    // Check arguments.
042.    if (Doc == null)
043.        throw new ArgumentException("Doc");
044.    if (Key == null)
045.        throw new ArgumentException("Key");
046. 
047.    try
048.    {
049.        // Create a SignedXml object to generate signature.
050.        SignedXml signedXml = new SignedXml(Doc);
051. 
052.        // Add the key to the SignedXml document
053.        signedXml.SigningKey = Key;
054. 
055.        // Create a reference to be signed
056.        Reference reference = new Reference();
057.        reference.Uri = "";
058. 
059.        // Add an enveloped transformation to the reference
060.        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
061.        reference.AddTransform(env);
062. 
063.        // Add the reference to the SignedXml object
064.        signedXml.AddReference(reference);
065. 
066.        // Compute the signature
067.        signedXml.ComputeSignature();
068. 
069.        // Get the XML representation of the signature and save
070.        // it to an XmlElement object.
071.        XmlElement xmlDigitalSignature = signedXml.GetXml();
072. 
073.        // Append the element to the XML document.
074.        Doc.DocumentElement.AppendChild(Doc.ImportNode(xmlDigitalSignature, true));
075.    }
076.    catch (Exception ex)
077.    {
078.        MessageBox.Show(ex.Message);
079.    }
080.}
081. 
082.private void btnVerify_Click(object sender, EventArgs e)
083.{
084.    /////////////////////////////////////////////////////////////////////
085.    // Create a new RSA signing key and import public key for
086.    // verification.
087.    //
088. 
089.    //NOTE:Public RSA Key를 이용해서 RSACryptoService Generate
090.    RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider();
091.    rsaKey.FromXmlString(publicOnlyKey);
092.    /////////////////////////////////////////////////////////////////////
093.    // Load the signed XML, and call VerifyXml to verify the signature of
094.    // the signed XML.
095.    //
096. 
097.    XmlDocument xmlDoc = new XmlDocument();
098.    xmlDoc.Load("test1.xml");
099. 
100.    bool result = VerifyXml(xmlDoc, rsaKey);
101. 
102.    if (result)
103.    {
104.        MessageBox.Show("The XML signature is valid.");
105.    }
106.    else
107.    {
108.        MessageBox.Show("The XML signature is not valid.");
109.    }
110.}
111. 
112.public static Boolean VerifyXml(XmlDocument Doc, RSA Key)
113.{
114.    // Check arguments.
115.    if (Doc == null)
116.        throw new ArgumentException("Doc");
117.    if (Key == null)
118.        throw new ArgumentException("Key");
119. 
120. 
121.    /////////////////////////////////////////////////////////////////////
122.    // Create a SignedXml object to verify the signature
123.    //
124. 
125.    SignedXml signedXml = new SignedXml(Doc);
126. 
127.    // Find Signature node and create a new XmlNodeList object
128.    XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");
129. 
130.    // Throw an exception if no signature was found.
131.    if (nodeList.Count <= 0)
132.    {
133.        throw new CryptographicException(
134.            "Verification failed:" +
135.            " No Signature was found in the document.");
136.    }
137. 
138.    // This example only supports one signature for entire XML document
139.    if (nodeList.Count >= 2)
140.    {
141.        throw new CryptographicException(
142.            "Verification failed: More that one signature was found.");
143.    }
144. 
145.    // Load the first <signature> node. 
146.    signedXml.LoadXml((XmlElement)nodeList[0]);
147. 
148.    // Check the signature and return the result.
149.    return signedXml.CheckSignature(Key);
150.}
151. 
152.private void btnChangeXML_Click(object sender, EventArgs e)
153.{
154.    // Modify the value of the Xml document for test.
155. 
156.    XDocument xDoc = XDocument.Load("test1.xml");
157. 
158.    if (xDoc != null)
159.    {
160.        xDoc.Element("invoice").Element("items").
161.            Element("creditcard").Element("number").SetValue("19834210");
162. 
163.        xDoc.Save("test1.xml");
164. 
165.        tbxModifiedMessage.Text = xDoc.ToString();
166.    }
167.}
168.</signature>
Posted by Y2K
,

0004. XmlGeneral

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


001./****************************** Module Header ******************************\
002.* Module Name:  Program.cs
003.* Project:      CSXmlGeneral
004.* Copyright (c) Microsoft Corporation.
005.*
006.* This C# sample project shows how to read a XML file by using XmlTextReader
007.* or XmlNodeReader. It also shows, instead of using forward-only reader, how
008.* to read, modify, and update Xml element using the XmlDocument class. This
009.* class will load the whole document into memory for modification and we can
010.* save the modified XML file to the file system.
011.*
012.* The XML file used by the demo has this format:
013.*
014.* <catalog>
015.*  <book id="bk101">
016.*    <author>Gambardella, Matthew</author>
017.*    <title>XML Developer's Guide</title>
018.*    <genre>Computer</genre>
019.*    <price>44.95</price>
020.*    <publish_date>2000-10-01</publish_date>
021.*    <description>
022.*      An in-depth look at creating applications
023.*      with XML.
024.*    </description>
025.*  </book>
026.*  <book>
027.*   ...
028.*  </book>
029.* <catalog>
030.*
031.* This source is subject to the Microsoft Public License.
033.* All other rights reserved.
034.*
035.* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
036.* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
037.* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
038.\***************************************************************************/
039. 
040.#region Using directives
041.using System;
042.using System.Collections.Generic;
043.using System.Linq;
044.using System.Text;
045.using System.Xml;
046.#endregion
047. 
048. 
049.class Program
050.{
051.    static void Main(string[] args)
052.    {
053.        /////////////////////////////////////////////////////////////////////
054.        // Read XML document using the XmlTextReader class.
055.        //
056. 
057.        // The XmlTextReader acts as a reader pointer that only moves forward.
058.        // Because it always moves forward and read a piece of data into
059.        // memory buffer, it has better performance than the XmlDocument
060.        // class which loads the whole document into memory.
061. 
062.        Console.WriteLine("Loading XML using XmlTextReader...");
063. 
064.        XmlTextReader xmlTextReader = new XmlTextReader(@"Books.xml");
065.        xmlTextReader.WhitespaceHandling = WhitespaceHandling.None;
066. 
067.        while (xmlTextReader.Read())
068.        {
069.            if (xmlTextReader.Name == "book")
070.            {
071.                Console.WriteLine(xmlTextReader.GetAttribute("id") + ": ");
072. 
073.                xmlTextReader.Read();
074.                string author = xmlTextReader.ReadElementContentAsString();
075.                string title = xmlTextReader.ReadElementContentAsString();
076.                string genre = xmlTextReader.ReadElementContentAsString();
077.                string price = xmlTextReader.ReadElementContentAsString();
078.                string publishDate = xmlTextReader.ReadElementContentAsString();
079.                string description = xmlTextReader.ReadElementContentAsString();
080. 
081.                Console.WriteLine(genre + " book \"" + title + "\" written by \"" +
082.                    author + "\", published on " + publishDate);
083.                Console.WriteLine(description);
084.            }
085.        }
086. 
087.        xmlTextReader.Close();
088. 
089. 
090.        /////////////////////////////////////////////////////////////////////
091.        // Read XML document using the XmlDocument and XmlNodeReader classes.
092.        //
093. 
094.        // XmlNodeReader is similar to XmlTextReader but accepts an XmlNode
095.        // instance as target to read. The following code shows how to use
096.        // XmlDocument and XmlNodeReader to retrieve XML information. It is
097.        // also a forward-only reader.
098. 
099.        Console.WriteLine("Loading XML using XmlDocument & XmlNodeReader...");
100. 
101.        XmlDocument xmlDocument = new XmlDocument();
102.        xmlDocument.Load(@"Books.xml");
103.        XmlNodeList xmlNodes = xmlDocument.GetElementsByTagName("book");
104.        foreach (XmlNode node in xmlNodes)
105.        {
106.            Console.WriteLine(node.Attributes["id"].Value + ":");
107. 
108.            XmlNodeReader xmlNodeReader = new XmlNodeReader(node);
109.            xmlNodeReader.Read();
110.            xmlNodeReader.Read();
111.            string author = xmlNodeReader.ReadElementContentAsString();
112.            string title = xmlNodeReader.ReadElementContentAsString();
113.            string genre = xmlNodeReader.ReadElementContentAsString();
114.            string price = xmlNodeReader.ReadElementContentAsString();
115.            string publishDate = xmlNodeReader.ReadElementContentAsString();
116.            string description = xmlNodeReader.ReadElementContentAsString();
117. 
118.            Console.WriteLine(genre + " book \"" + title + "\" written by \"" +
119.                author + "\", published on " + publishDate);
120.            Console.WriteLine(description);
121.        }
122. 
123. 
124.        /////////////////////////////////////////////////////////////////////
125.        // Make changes to the XmlDocument.
126.        //
127. 
128.        // Modify a node value by first calling SelectSingleNode to navigate
129.        // to that node and by setting its InnerText property to change its
130.        // content.
131.        XmlNode nodeToModify = xmlDocument.DocumentElement.SelectSingleNode(
132.            "book/genre");
133.        nodeToModify.InnerText = "XML Tech";
134. 
135.        // Add a new XML node. In XML programming, we always call
136.        // XMLDocument.Create*** to create an attribute or element. After
137.        // that, we can add it into where we want by calling Node.AppendChild
138.        XmlElement newElement = xmlDocument.CreateElement("book");
139.        XmlAttribute newAttribute = xmlDocument.CreateAttribute("id");
140.        newAttribute.Value = "bk103";
141.        XmlElement authorElement = xmlDocument.CreateElement("author");
142.        authorElement.InnerText = "Mark Russinovich,David Solomon,Alex Ionecsu";
143.        XmlElement titleElement = xmlDocument.CreateElement("title");
144.        titleElement.InnerText = "Windows Internals, 5th edition";
145.        XmlElement genreElement = xmlDocument.CreateElement("genre");
146.        genreElement.InnerText = "Windows Server 2008";
147.        XmlElement priceElement = xmlDocument.CreateElement("price");
148.        priceElement.InnerText = "69.99";
149.        XmlElement publishDateElement = xmlDocument.CreateElement("publish_date");
150.        publishDateElement.InnerText = "2009-6-17";
151.        XmlElement descriptionElement = xmlDocument.CreateElement("description");
152.        descriptionElement.InnerText = "Windows Internals, 5th edition is the" +
153.            " update to Windows Internals, 4th edition to cover Windows Vista" +
154.            " and Windows Server 2008 (32-bit and 64-bit).";
155. 
156.        newElement.Attributes.Append(newAttribute);
157.        newElement.AppendChild(authorElement);
158.        newElement.AppendChild(titleElement);
159.        newElement.AppendChild(genreElement);
160.        newElement.AppendChild(priceElement);
161.        newElement.AppendChild(publishDateElement);
162.        newElement.AppendChild(descriptionElement);
163.        xmlDocument.DocumentElement.AppendChild(newElement);
164. 
165.        // Save the changes
166.        xmlDocument.Save("Modified Books.xml");
167. 
168.        // XmlLDocument does not have Close or Dispose method because it is
169.        // an in-memory representation of an XML document. Once read, the
170.        // file is no-longer needed.
171.    }
172.}
173.</catalog></catalog>

01.<!--?xml version="1.0" encoding="utf-8" ?-->
02.<catalog>
03.  <book id="bk101">
04.    <author>Gambardella, Matthew</author>
05.    <title>XML Developer's Guide</title>
06.    <genre>Computer</genre>
07.    <price>44.95</price>
08.    <publish_date>2000-10-01</publish_date>
09.    <description>
10.      An in-depth look at creating applications
11.      with XML.
12.    </description>
13.  </book>
14.  <book id="bk102">
15.    <author>Ralls, Kim</author>
16.    <title>Midnight Rain</title>
17.    <genre>Fantasy</genre>
18.    <price>5.95</price>
19.    <publish_date>2000-12-16</publish_date>
20.    <description>
21.      A former architect battles corporate zombies,
22.      an evil sorceress, and her own childhood to become queen
23.      of the world.
24.    </description>
25.  </book>
26.</catalog>
Posted by Y2K
,
.NET에서 Serialization은 객체를 저장하고, 객체를 다시 불러오는데 매우 유용하다. 그리고 네트워크로 Serialization된 객체를 전송하고,
다시 그 객체를 사용할 수 도 있는 .NET에서 핵심적인 기능중 하나이다.

XmlSerialization을 하기 위해 가장 유의할 점은 생성자는 input parameter가 없는 생성자만이 가능하다는 점을 항시 알아야지 된다.
input parameter가 있는 경우에는 Runtime시에 exception이 발생되게 된다.


001./****************************** Module Header ******************************\
002.* Module Name:  Program.cs
003.* Project:      CSXmlSerialization
004.* Copyright (c) Microsoft Corporation.
005.*
006.* This sample shows how to serialize an in-memory object to a local xml file
007.* and how to deserialize the xml file back to an in-memory object using
008.* C#. The designed MySerializableType includes int, string, generic, as well
009.* as customized type field and property.
010.*
011.* This source is subject to the Microsoft Public License.
013.* All other rights reserved.
014.*
015.* History:
016.* * 7/29/2009 3:00 PM Colbert Zhou Created
017.* * 8/20/2009 12:01 AM Jialiang Ge Reviewed
018.\***************************************************************************/
019. 
020.#region Using directives
021.using System;
022.using System.Collections.Generic;
023.using System.Linq;
024.using System.Text;
025.using System.Xml;
026.using System.Xml.Serialization;
027.using System.IO;
028.using System.Collections;
029.#endregion
030. 
031. 
032.namespace CSXmlSerialization
033.{
034.    class Program
035.    {
036.        static void Main(string[] args)
037.        {
038.            /////////////////////////////////////////////////////////////////
039.            // Serialize the object to an XML file.
040.            //
041. 
042.            // Create and initialize a MySerializableType instance.
043.            MySerializableType instance = new MySerializableType();
044.            instance.BoolValue = true;
045.            instance.IntValue = 1;
046.            instance.StringValue = "Test String";
047.            instance.ListValue.Add("List Item 1");
048.            instance.ListValue.Add("List Item 2");
049.            instance.ListValue.Add("List Item 3");
050.            instance.AnotherTypeValue = new AnotherType();
051.            instance.AnotherTypeValue.IntValue = 2;
052.            instance.AnotherTypeValue.StringValue = "Inner Test String";
053. 
054.            // Create the serializer
055.            XmlSerializer serializer = new XmlSerializer(typeof(MySerializableType));
056. 
057.            // Serialize the object to an XML file
058.            using (StreamWriter streamWriter = File.CreateText(
059.                "CSXmlSerialization.xml"))
060.            {
061.                serializer.Serialize(streamWriter, instance);
062.            }
063. 
064. 
065.            /////////////////////////////////////////////////////////////////
066.            // Deserialize from a XML file to an object instance.
067.            //
068. 
069.            // Deserialize the object
070.            MySerializableType deserializedInstance;
071.            using (StreamReader streamReader = File.OpenText(
072.                "CSXmlSerialization.xml"))
073.            {
074.                deserializedInstance = serializer.Deserialize(streamReader)
075.                    as MySerializableType;
076.            }
077. 
078.            // Dump the object
079.            Console.WriteLine("BoolValue: {0}", deserializedInstance.BoolValue);
080.            Console.WriteLine("IntValue: {0}", deserializedInstance.IntValue);
081.            Console.WriteLine("StringValue: {0}", deserializedInstance.StringValue);
082.            Console.WriteLine("AnotherTypeValue.IntValue: {0}",
083.                deserializedInstance.AnotherTypeValue.IntValue);
084.            Console.WriteLine("AnotherTypeValue.StringValue: {0}",
085.                deserializedInstance.AnotherTypeValue.StringValue);
086.            Console.WriteLine("ListValue: ");
087.            foreach (object obj in deserializedInstance.ListValue)
088.            {
089.                Console.WriteLine(obj.ToString());
090.            }
091.        }
092.    }
093. 
094. 
095.    /// <summary>
096.    /// Serializable Type Declaration
097.    /// </summary>
098.    [Serializable()]
099.    public class MySerializableType
100.    {
101.        // String field and property
102.        private string stringValue;
103.        public string StringValue
104.        {
105.            get { return stringValue; }
106.            set { stringValue = value; }
107.        }
108. 
109.        // Bool field and property
110.        private bool boolValue;
111.        public bool BoolValue
112.        {
113.            get { return boolValue; }
114.            set { boolValue = value; }
115.        }
116. 
117.        // Int field and property
118.        private int intValue;
119.        public int IntValue
120.        {
121.            get { return intValue; }
122.            set { intValue = value; }
123.        }
124. 
125.        // Another type field and property
126.        private AnotherType anotherTypeValue;
127.        public AnotherType AnotherTypeValue
128.        {
129.            get { return anotherTypeValue; }
130.            set { anotherTypeValue = value; }
131.        }
132. 
133.        // Generic type field and property
134.        private List<string> listValue = new List<string>();
135.        public List<string> ListValue
136.        {
137.            get { return listValue; }
138.            set { listValue = value; }
139.        }
140. 
141.        // Ignore a field using NonSerialized attribute
142.        [NonSerialized()]
143.        private int ignoredField = 1;
144.    }
145. 
146.    /// <summary>
147.    /// Another Type Declaration
148.    /// </summary>
149.    [Serializable()]
150.    public class AnotherType
151.    {
152.        private string stringValue;
153.        public string StringValue
154.        {
155.            get { return stringValue; }
156.            set { stringValue = value; }
157.        }
158. 
159.        private int intValue;
160.        public int IntValue
161.        {
162.            get { return intValue; }
163.            set { intValue = value; }
164.        }
165.    }
166.}
167.</string></string></string>
Posted by Y2K
,

0002. CSXPath

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

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


001./****************************** Module Header ******************************\
002.* Module Name:  Program.cs
003.* Project:      CSXPath
004.* Copyright (c) Microsoft Corporation.
005.*
006.* This sample project shows how to use XPathDocument class to load the XML
007.* file and manipulate. It includes two main parts, XPathNavigator usage and
008.* XPath Expression usage. The first part shows how to use XPathNavigator to
009.* navigate through the whole document, read its content. The second part
010.* shows how to use XPath expression to filter information and select it out.
011.*
012.* This source is subject to the Microsoft Public License.
014.* All other rights reserved.
015.*
016.* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
017.* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
018.* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
019.\***************************************************************************/
020. 
021.using System;
022.using System.Collections.Generic;
023.using System.Linq;
024.using System.Text;
025.using System.Xml;
026.using System.Xml.XPath;
027. 
028. 
029.namespace CSXPath
030.{
031.    class Program
032.    {
033.        static void Main(string[] args)
034.        {
035.            #region Initialize XPathDocument and XPathNavigator
036. 
037.            XPathNavigator xPathNavigator;
038.            XPathDocument xPathDoc;
039.             
040.            //Navigate through the whole document
041.            //Create a new instance of XPathDocument from a XML file
042.            xPathDoc = new XPathDocument("books.xml");
043. 
044.            //Call CreateNavigator method to create a navigator instance
045.            //And we will use this navigator object to navigate through whole document
046.            xPathNavigator = xPathDoc.CreateNavigator();
047.             
048.            #endregion
049. 
050.            #region Navigate through the document
051. 
052.            //Move to the root element
053.            xPathNavigator.MoveToRoot();
054.            //Catalog element is the first children of the root
055.            //Move to catalog element
056.            xPathNavigator.MoveToFirstChild();
057.            //We can know a XML node's type from the NodeType property
058.            //XPathNodeType has Attribute, Element, Namespace and so on
059.            if (xPathNavigator.NodeType == XPathNodeType.Element)
060.            {
061.                //We can know if a Node has child nodes by checking its
062.                //HasChildren property. If it returns true, that node has
063.                //child nodes
064.                if (xPathNavigator.HasChildren == true)
065.                {
066.                    //Move to the first child which is our first book nodes
067.                    xPathNavigator.MoveToFirstChild();
068.                    do
069.                    {
070.                        //We can know if a node has any attribute by checking
071.                        //the HasAttributes property. When this property returns
072.                        //true, we can get the specified attribute by calling
073.                        //navigator.GetAttribute() method
074.                        if (xPathNavigator.HasAttributes == true)
075.                        {
076.                            Console.WriteLine("Book ID: " + xPathNavigator.GetAttribute("id", ""));
077.                        }
078. 
079.                        //Iterate through a book node's child nodes
080.                        //and list all child node information, like
081.                        //name, author, price, publish date and so on
082.                        if (xPathNavigator.HasChildren)
083.                        {
084.                            xPathNavigator.MoveToFirstChild();
085.                            do
086.                            {
087.                                Console.Write("\t{0}:\t{1}\r\n", xPathNavigator.Name, xPathNavigator.Value);
088.                            } while (xPathNavigator.MoveToNext());
089.                            //When all child nodes are reached. The MoveToNext() method returns
090.                            //false. Then we need to call MoveToParent to go back to the book level
091.                            xPathNavigator.MoveToParent();
092.                        }
093.                        //Move to the next book element.
094.                    } while (xPathNavigator.MoveToNext());
095.                }
096.            }
097. 
098.            #endregion
099. 
100.            #region Use of XPath Expression
101.             
102.            //Use XPath Expression to select out book bk103
103.            //The expression should be "/catalog/book[@id='bk103']"
104.            //@ means to look id attribute and match bk103
105.            Console.WriteLine("Use XPath Expression to select out the book with ID bk103:");
106.            XPathExpression expression = xPathNavigator.Compile("/catalog/book[@id='bk103']");
107.            XPathNodeIterator iterator = xPathNavigator.Select(expression);
108. 
109.            //After compile the XPath expression, we can call navigator.Select
110.            //to retrieve the XPathNodeIterator. With this interator, we can loop
111.            //trough the results filtered by the XPath expression
112.            //The following codes print the book bk103's detailed information
113.             
114.            while (iterator.MoveNext())
115.            {
116.                XPathNavigator nav = iterator.Current.Clone();
117.                Console.WriteLine("Book ID: " + nav.GetAttribute("id", ""));
118.                if (nav.HasChildren)
119.                {
120.                    nav.MoveToFirstChild();
121.                    do
122.                    {
123.                        Console.Write("\t{0}:\t{1}\r\n", nav.Name, nav.Value);
124.                    } while (nav.MoveToNext());
125.                }
126.            }
127. 
128. 
129.            //Use XPath to select out all books whose price are more than 10.00
130.            // '[]' means to look into the child node to match the condition "price > 10"
131.            Console.WriteLine("\r\nUse XPath Expression to select out all books whose price are more than 10:");
132.            expression = xPathNavigator.Compile("/catalog/book[price>10]");
133.            iterator = xPathNavigator.Select(expression);
134. 
135.            //After getting the iterator, we print title and price for books
136.            //whose price are more than 10
137.            while (iterator.MoveNext())
138.            {
139.                XPathNavigator nav = iterator.Current.Clone();
140.                Console.WriteLine("Book ID: " + nav.GetAttribute("id", ""));
141.                if (nav.HasChildren)
142.                {
143.                    nav.MoveToFirstChild();
144.                    do
145.                    {
146.                        if (nav.Name == "title")
147.                        {
148.                            Console.Write("\t{0}:\t{1}\r\n", nav.Name, nav.Value);
149.                        }
150.                        if (nav.Name == "price")
151.                        {
152.                            Console.Write("\t{0}:\t{1}\r\n", nav.Name, nav.Value);
153.                        }
154.                    } while (nav.MoveToNext());
155.                }
156.            }
157. 
158.            //Use XPath Expression to calculate the average price of all books.
159.            //Here in XPath, we use the sum, div, and count formula.
160.            Console.WriteLine("\r\nUse XPath Expression to calculate the average price of all books:");
161.            expression = xPathNavigator.Compile("sum(/catalog/book/price) div count(/catalog/book/price)");
162.            string averagePrice = xPathNavigator.Evaluate(expression).ToString();
163.            Console.WriteLine("The average price of the books are {0}", averagePrice);
164. 
165. 
166.            #endregion
167. 
168.            #region End. Read a char to exit
169. 
170.            Console.WriteLine("Input any key to quit the sample application");
171.            Console.ReadLine();
172. 
173.            #endregion
174.        }
175.    }
176.}

001.<!--?xml version="1.0"?-->
002.<catalog>
003.  <book id="bk101">
004.    <author>Gambardella, Matthew</author>
005.    <title>XML Developer's Guide</title>
006.    <genre>Computer</genre>
007.    <price>44.95</price>
008.    <publish_date>2000-10-01</publish_date>
009.    <description>
010.      An in-depth look at creating applications
011.      with XML.
012.    </description>
013.  </book>
014.  <book id="bk102">
015.    <author>Ralls, Kim</author>
016.    <title>Midnight Rain</title>
017.    <genre>Fantasy</genre>
018.    <price>5.95</price>
019.    <publish_date>2000-12-16</publish_date>
020.    <description>
021.      A former architect battles corporate zombies,
022.      an evil sorceress, and her own childhood to become queen
023.      of the world.
024.    </description>
025.  </book>
026.  <book id="bk103">
027.    <author>Corets, Eva</author>
028.    <title>Maeve Ascendant</title>
029.    <genre>Fantasy</genre>
030.    <price>5.95</price>
031.    <publish_date>2000-11-17</publish_date>
032.    <description>
033.      After the collapse of a nanotechnology
034.      society in England, the young survivors lay the
035.      foundation for a new society.
036.    </description>
037.  </book>
038.  <book id="bk104">
039.    <author>Corets, Eva</author>
040.    <title>Oberon's Legacy</title>
041.    <genre>Fantasy</genre>
042.    <price>5.95</price>
043.    <publish_date>2001-03-10</publish_date>
044.    <description>
045.      In post-apocalypse England, the mysterious
046.      agent known only as Oberon helps to create a new life
047.      for the inhabitants of London. Sequel to Maeve
048.      Ascendant.
049.    </description>
050.  </book>
051.  <book id="bk105">
052.    <author>Corets, Eva</author>
053.    <title>The Sundered Grail</title>
054.    <genre>Fantasy</genre>
055.    <price>5.95</price>
056.    <publish_date>2001-09-10</publish_date>
057.    <description>
058.      The two daughters of Maeve, half-sisters,
059.      battle one another for control of England. Sequel to
060.      Oberon's Legacy.
061.    </description>
062.  </book>
063.  <book id="bk106">
064.    <author>Randall, Cynthia</author>
065.    <title>Lover Birds</title>
066.    <genre>Romance</genre>
067.    <price>4.95</price>
068.    <publish_date>2000-09-02</publish_date>
069.    <description>
070.      When Carla meets Paul at an ornithology
071.      conference, tempers fly as feathers get ruffled.
072.    </description>
073.  </book>
074.  <book id="bk107">
075.    <author>Thurman, Paula</author>
076.    <title>Splish Splash</title>
077.    <genre>Romance</genre>
078.    <price>4.95</price>
079.    <publish_date>2000-11-02</publish_date>
080.    <description>
081.      A deep sea diver finds true love twenty
082.      thousand leagues beneath the sea.
083.    </description>
084.  </book>
085.  <book id="bk108">
086.    <author>Knorr, Stefan</author>
087.    <title>Creepy Crawlies</title>
088.    <genre>Horror</genre>
089.    <price>4.95</price>
090.    <publish_date>2000-12-06</publish_date>
091.    <description>
092.      An anthology of horror stories about roaches,
093.      centipedes, scorpions  and other insects.
094.    </description>
095.  </book>
096.  <book id="bk109">
097.    <author>Kress, Peter</author>
098.    <title>Paradox Lost</title>
099.    <genre>Science Fiction</genre>
100.    <price>6.95</price>
101.    <publish_date>2000-11-02</publish_date>
102.    <description>
103.      After an inadvertant trip through a Heisenberg
104.      Uncertainty Device, James Salway discovers the problems
105.      of being quantum.
106.    </description>
107.  </book>
108.  <book id="bk110">
109.    <author>O'Brien, Tim</author>
110.    <title>Microsoft .NET: The Programming Bible</title>
111.    <genre>Computer</genre>
112.    <price>36.95</price>
113.    <publish_date>2000-12-09</publish_date>
114.    <description>
115.      Microsoft's .NET initiative is explored in
116.      detail in this deep programmer's reference.
117.    </description>
118.  </book>
119.  <book id="bk111">
120.    <author>O'Brien, Tim</author>
121.    <title>MSXML3: A Comprehensive Guide</title>
122.    <genre>Computer</genre>
123.    <price>36.95</price>
124.    <publish_date>2000-12-01</publish_date>
125.    <description>
126.      The Microsoft MSXML3 parser is covered in
127.      detail, with attention to XML DOM interfaces, XSLT processing,
128.      SAX and more.
129.    </description>
130.  </book>
131.  <book id="bk112">
132.    <author>Galos, Mike</author>
133.    <title>Visual Studio 7: A Comprehensive Guide</title>
134.    <genre>Computer</genre>
135.    <price>49.95</price>
136.    <publish_date>2001-04-16</publish_date>
137.    <description>
138.      Microsoft Visual Studio 7 is explored in depth,
139.      looking at how Visual Basic, Visual C++, C#, and ASP+ are
140.      integrated into a comprehensive development
141.      environment.
142.    </description>
143.  </book>
144.</catalog>
Posted by 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 하는 간단한 예제를 보이고 있다.


 

01.<catalog>
02.  <book id="bk101">
03.    <author>Gambardella Matthew</author>
04.    <title>XML Developer's Guide</title>
05.    <genre>Computer</genre>
06.    <price>44.95</price>
07.    <publish_date>2000-10-01</publish_date>
08.    <description>An in-depth look at creating applications with XML.</description>
09.  </book>
10.  <book id="bk102">
11.    <author>Ralls Kim</author>
12.    <title>Midnight Rain</title>
13.    <genre>Fantasy</genre>
14.    <price>5.95</price>
15.    <publish_date>2000-12-16</publish_date>
16.    <description>A former architect battles corporate zombies and her own childhood to become queen of the world.</description>
17.  </book>
18.  <book id="bk103">
19.    <author>Corets Eva</author>
20.    <title>Maeve Ascendant</title>
21.    <genre>Fantasy</genre>
22.    <price>5.95</price>
23.    <publish_date>2000-11-17</publish_date>
24.    <description>After the collapse of a nanotechnology society in England the young survivors lay the foundation for a new society.</description>
25.  </book>
26.  <book id="bk104">
27.    <author>Corets Eva</author>
28.    <title>Oberon's Legacy</title>
29.    <genre>Fantasy</genre>
30.    <price>5.95</price>
31.    <publish_date>2001-03-10</publish_date>
32.    <description>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.</description>
33.  </book>
34.  <book id="bk105">
35.    <author>Corets Eva</author>
36.    <title>The Sundered Grail</title>
37.    <genre>Fantasy</genre>
38.    <price>5.95</price>
39.    <publish_date>2001-09-10</publish_date>
40.    <description>The two daughters of Maeve half-sisters battle one another for control of England. Sequel to Oberon's Legacy.</description>
41.  </book>
42.  <book id="bk106">
43.    <author>Randall Cynthia</author>
44.    <title>Lover Birds</title>
45.    <genre>Romance</genre>
46.    <price>4.95</price>
47.    <publish_date>2000-09-02</publish_date>
48.    <description>When Carla meets Paul at an ornithology conference tempers fly as feathers get ruffled.</description>
49.  </book>
50.  <book id="bk107">
51.    <author>Thurman Paula</author>
52.    <title>Splish Splash</title>
53.    <genre>Romance</genre>
54.    <price>4.95</price>
55.    <publish_date>2000-11-02</publish_date>
56.    <description>A deep sea diver finds true love twenty thousand leagues beneath the sea.</description>
57.  </book>
58.  <book id="bk108">
59.    <author>Knorr Stefan</author>
60.    <title>Creepy Crawlies</title>
61.    <genre>Horror</genre>
62.    <price>4.95</price>
63.    <publish_date>2000-12-06</publish_date>
64.    <description>An anthology of horror stories about roaches centipedes scorpions  and other insects.</description>
65.  </book>
66.  <book id="bk109">
67.    <author>Kress Peter</author>
68.    <title>Paradox Lost</title>
69.    <genre>Science Fiction</genre>
70.    <price>6.95</price>
71.    <publish_date>2000-11-02</publish_date>
72.    <description>After an inadvertant trip through a Heisenberg Uncertainty Device James Salway discovers the problems of being quantum.</description>
73.  </book>
74.  <book id="bk110">
75.    <author>O'Brien Tim</author>
76.    <title>Microsoft .NET: The Programming Bible</title>
77.    <genre>Computer</genre>
78.    <price>36.95</price>
79.    <publish_date>2000-12-09</publish_date>
80.    <description>Microsoft's .NET initiative is explored in detail in this deep programmer's reference.</description>
81.  </book>
82.  <book id="bk111">
83.    <author>O'Brien Tim</author>
84.    <title>MSXML3: A Comprehensive Guide</title>
85.    <genre>Computer</genre>
86.    <price>36.95</price>
87.    <publish_date>2000-12-01</publish_date>
88.    <description>The Microsoft MSXML3 parser is covered in detail with attention to XML DOM interfaces XSLT processing SAX and more.</description>
89.  </book>
90.  <book id="bk112">
91.    <author>Galos Mike</author>
92.    <title>Visual Studio 7: A Comprehensive Guide</title>
93.    <genre>Computer</genre>
94.    <price>49.95</price>
95.    <publish_date>2001-04-16</publish_date>
96.    <description>Microsoft Visual Studio 7 is explored in depth looking at how Visual Basic/Visual C++/C#/ASP+ are integrated into a comprehensive development environment.</description>
97.  </book>
98.</catalog>

01.<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
02.    <xsl:output method="text">
03.    <xsl:template match="catalog">
04.      <xsl:apply-templates select="book">
05.    </xsl:apply-templates>
06.    <xsl:template match="book">
07.      <xsl:text>"</xsl:text>
08.      <xsl:value-of select="@id">
09.      <xsl:text>"</xsl:text>
10.      <xsl:value-of select="','">
11.      <xsl:for-each select="*">
12.        <xsl:text>"</xsl:text>
13.        <xsl:value-of select=".">
14.        <xsl:text>"</xsl:text>
15.        <xsl:if test="position() != last()">
16.          <xsl:value-of select="','">
17.        </xsl:value-of>
18.      </xsl:if>
19.      <xsl:text>
20. 
21.</xsl:text>
22.    </xsl:value-of>
23.</xsl:for-each>
24.</xsl:value-of></xsl:value-of></xsl:template></xsl:template></xsl:output></xsl:stylesheet>

01.#region Using directives
02.using System;
03.using System.Collections.Generic;
04.using System.Text;
05.using System.Xml.Xsl;
06.#endregion
07. 
08. 
09.namespace CSXslTransformXml
10.{
11.    class Program
12.    {
13.        static void Main(string[] args)
14.        {
15.            XslCompiledTransform transform = new XslCompiledTransform();
16.            transform.Load("Books.xslt");
17.            transform.Transform("Books.xml", "Books.csv");
18.        }
19.    }
20.}
Posted by Y2K
,

Pro LINQ (07)

Book 2009. 1. 15. 02:32
XML Schema(*.xsd)파일을 이용한 XML의 Validation과 기존의 XmlDocument에서 지원되는 XPath 역시 같이 지원 가능하다. 또한, 제공되는 XML을 통한 XML Schema를 역으로 얻어내는 방법을 같이 제공하고 있다. 

var xDocument = new XDocument();
var rootElement = new XElement("BookParticipants");

var bookElement1 = new XElement("BookParticipant");
bookElement1.Add(new XAttribute("type", "Author"));
bookElement1.Add(new XElement("FirstName", "Joe"));
bookElement1.Add(new XElement("LastName", "Rattz"));
rootElement.Add(bookElement1);

var bookElement2 = new XElement("BookParticipant");
bookElement2.Add(new XAttribute("type", "Editor"));
bookElement2.Add(new XElement("FirstName", "Ewan"));
bookElement2.Add(new XElement("LastName", "Buckingham"));
rootElement.Add(bookElement2);

xDocument.Add(rootElement);
xDocument.Save("bookparticipants.xml");

XmlSchemaInference infer = new XmlSchemaInference();
XmlSchemaSet schemaSet = infer.InferSchema(XmlReader.Create("bookparticipants.xml"));
XmlWriter xmlWriter = XmlWriter.Create("bookparticipants.xsd");

foreach(XmlSchema xmlSchema in schemaSet.Schemas())
{
    xmlSchema.Write(xmlWriter);
}
xmlWriter.Close();

XDocument schemaDocument = XDocument.Load("bookparticipants.xsd");
Console.WriteLine(schemaDocument);

정말로 대단한 기능이라고 생각이 되는 것이, XML 파일만 있더라고 그 안에서 XSD의 추론이 가능해지기 때문에, 그 응용을 어떤 방향으로 솔찍히 해줘야지 될지 잘은 모르겠다는 생각이 든다. 아직 XSD를 잘 사용을 안하고 있는 것이 잘 모르고 있는 이유중 하나일 것 같다.

XML의 Validation은 다음과 같이 할 수 있다. 기존의 XmlDocument와 코드가 완전히 동일하다.
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add(string.Empty, "bookparticipants.xsd");
try
{
    xDocument.Validate(schemaSet, null);
    Console.WriteLine("Document validated successfully");
}
catch(XmlSchemaValidationException ex)
{
    Console.WriteLine(ex.Message);
}


마지막으로 XDocument에서의 XPath 사용을 간략한 예이다.
xDocument.Add(rootElement);
XElement xElement = xDocument.XPathSelectElement("//BookParticipants/BookParticipant[FirstName='Joe']");
Console.WriteLine(string.Format("Selected Element : {0} / {1}", xElement.Name, xElement.Value));




Posted by Y2K
,
1. XDocument to XmlDocument
            XDocument xDocument = new XDocument();
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(xDocument.CreateReader());

2. XmlDocument to XDocument
            StringReader sr = new StringReader(xmlDoc.InnerXml);
            XDocument xDocument = XDocument.Load(XmlReader.Create(sr));


Posted by Y2K
,

어제 책을 읽다가 기존에 사용하고 있던 일반적인 text 형태의 Error reporter를 조금 예쁘게 만들어보고 싶다는 생각이 들어서 급조한 소스. 

xslt에 대한 포멧을 아직은 정확히 알지를 못해서 좀더 공부를 해볼 필요가 있을것 같다.
무엇보다 모든 일에 대한 표준화를 제공해줄수 있다는 점에서 가장 큰 장점을 가지고 있는듯. 

Class Source
    using System.Net.Mail;
    using System.Xml;
    using System.Xml.Linq;
    using System.IO;
    using System.Xml.Xsl;

    public class ExceptionReporter
    {
        private readonly Exception reportedException;
        public ExceptionReporter(Exception ex)
        {
            reportedException = ex;
        }

        public string ConvertXml()
        {
            XDocument xDocument = new XDocument();
            XElement rootElement = new XElement("Exceptions");
            XElement element = new XElement("ExceptionInfo");
            
            rootElement.Add(element);
            element.Add(new XElement("ExceptionType", reportedException.GetType().ToString()));
            element.Add(new XElement("Message", reportedException.Message));
            element.Add(new XElement("Source", reportedException.Source));
            element.Add(new XElement("TargetSite", reportedException.TargetSite));
            element.Add(new XElement("StackTrace", reportedException.StackTrace));
            xDocument.Add(rootElement);
            
            string xsl = File.ReadAllText("ErrorReporter.xslt");
            XDocument transformedDoc = new XDocument();
            using(XmlWriter xmlWriter = transformedDoc.CreateWriter())
            {
                XslCompiledTransform transform = new XslCompiledTransform();
                transform.Load(XmlReader.Create(new StringReader(xsl)));
                transform.Transform(xDocument.CreateReader(), xmlWriter);
            }
            return transformedDoc.ToString();
        }

        public bool SendEmailToManager()
        {
            SmtpClient client = new SmtpClient("smtpAddress");
            MailMessage mailMessage = new MailMessage();
            mailMessage.Subject = "Subject";
            mailMessage.IsBodyHtml = true;
            mailMessage.Body = ConvertXml();
            mailMessage.From = new MailAddress("fromMailAddress");
            mailMessage.To.Add(new MailAddress("toMailAddress"));
            client.Send(mailMessage);

            return true;
        }
    }


XSLT File
<?xml version='1.0' encoding='utf-8'?>
<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
  <xsl:output method='html'/>
  <xsl:template match='/'>
    <body>
      <xsl:apply-templates/>
    </body>    
  </xsl:template>

  <xsl:template match='ExceptionInfo'>
    <table width="100%" bgcolor="#d1d9e4" cellspacing="1" cellpadding="3">
      <tr>
        <td bgcolor="#666666" colspan="2">
          <font face="Arial" color="white">
            <b>Error Information</b>
          </font>
        </td>
      </tr>
      <tr bgcolor="#d0d0d0">
        <th>Parameter</th>
        <th>Data</th>
      </tr>
    <xsl:apply-templates />      
    </table>
  </xsl:template>
  <xsl:template match='ExceptionType'>
    <tr valign="top" bgcolor="white">
      <td>Exception Type</td>
      <td><xsl:apply-templates/></td>
    </tr>
  </xsl:template>  
  <xsl:template match='Message'>
    <tr valign="top" bgcolor="#f4f4f4">
      <td>Message</td>
      <td>
        <xsl:apply-templates/>
      </td>
    </tr>
  </xsl:template>
  <xsl:template match='Source'>
    <tr valign="top" bgcolor="white">
      <td>Source</td>
      <td><xsl:apply-templates/></td>
    </tr>
  </xsl:template>
  <xsl:template match="TargetSite">
    <tr valign="top" bgcolor="#f4f4f4">
      <td>TargetSite</td>
      <td><xsl:apply-templates/></td>
    </tr>    
  </xsl:template>
  <xsl:template match="StackTrace">
    <tr valign="top" bgcolor="white">
      <td>Stack Trace</td>
      <td><xsl:apply-imports/></td>
    </tr>
  </xsl:template>
</xsl:stylesheet>


사용 예제 : 
            try
            {
                File.ReadAllText("C:\\afwqerqwer.txt");
            }
            catch(Exception ex)
            {
                ExceptionReporter reporter = new ExceptionReporter(ex);
                reporter.SendEmailToManager();
                //Console.WriteLine(reporter.ConvertXml());
            }


결과:




Posted by Y2K
,
XElement를 이용하면 XmlDocument를 이용한 XmlDocument의 생성보다 편하고 직관적인 방법을 제공할 수 있다.

XElement - Element 생성
XComment - Comments 생성
XDeclaration - Declaration 생성

    public class XmlLinq2
    {
        public void CreateXmlDocument()
        {
            XNamespace nameSpace = "http://www.hostway.co.kr";
            XElement xBookParticipant = new XElement(nameSpace + "BookParticipant");
            XAttribute bookAttribute = new XAttribute("type", "Author");
            XElement xFirstname = new XElement(nameSpace + "FirstName", "Joe");
            XElement xLastName = new XElement(nameSpace + "LastName", "Rattz");
            XComment xComment = new XComment("This is XComment");

            xBookParticipant.Add(bookAttribute);
            xBookParticipant.Add(xComment);
            xBookParticipant.Add(xFirstname);
            xBookParticipant.Add(xLastName);

            Console.WriteLine(xBookParticipant);
        }

        public void FindDatas()
        {
            XNamespace nameSpace = "http://www.hostway.co.kr";
            XElement xBookParticipant = new XElement(nameSpace + "BookParticipant", 
                                                     new XElement(nameSpace + "FirstName", "Joe"),
                                                     new XElement(nameSpace + "LastName", "Rattz"));
            Console.WriteLine(xBookParticipant.ToString());
            Console.WriteLine(xBookParticipant);
        }
    }

: 기초책을 볼때마다 느끼는 거지만.. 언제나 기본인 내용을 모르고 있는 내 모습이 많이 부끄러워질때가 많은 것 같다. 


Posted by Y2K
,