블로그 이미지
Every unexpected event is a path to learning for you.

카테고리

분류 전체보기 (2735)
Unity3D (815)
Programming (474)
Server (33)
Unreal (4)
Gamebryo (56)
Tip & Tech (228)
협업 (58)
3DS Max (3)
Game (12)
Utility (136)
Etc (96)
Link (32)
Portfolio (19)
Subject (90)
iOS,OSX (53)
Android (14)
Linux (5)
잉여 프로젝트 (2)
게임이야기 (3)
Memories (20)
Interest (38)
Thinking (38)
한글 (30)
PaperCraft (5)
Animation (408)
Wallpaper (2)
재테크 (18)
Exercise (3)
나만의 맛집 (3)
냥이 (10)
육아 (16)
Total
Today
Yesterday
04-16 09:10

File stream과 XmlDocument class를 이용하는 방법입니다.

파일을 모두 읽어서 메모리로 로드하고, 메모리의 데이터를 읽기, 쓰기, 수정, 삭제 등을 하고 다시 파일로 저장하는 방식입니다.

데이터가 그리 크지 않을 경우 적당해 보이고, 파일이 클 경우 메모리 압박이 예상 됩니다.

 

출처: http://www.codeguru.com/Csharp/Csharp/cs_data/xml/article.php/c9427/

Downloads: SourceCode.zip - Download source code - 3 Kb

Display Contents of XML File

Listing 1 shows a simple XML file for demonstration:

Listing 1

<?xml version="1.0"?>
<Books>
  <Book ID="001">
    <Author>Mark</Author>
    <Publisher>Sams</Publisher>
  </Book>

  <Book ID="002">
    <Author>Joe</Author>
    <Publisher>AWL</Publisher>
  </Book>
</Books>

To test the above XML file for errors, simply open it with your browser. If it has no errors, the file will be displayed as such.

The next step is to display all the data using a C# console application (see Listing 2).

Listing 2: DisplayCatalog.cs

XmlNodeList xmlnode = xmldoc.GetElementsByTagName("Book");
   Console.WriteLine("Here is the list of catalogs\n\n");

   for(int i=0;i<xmlnode.Count;i++)
   {
   XmlAttributeCollection xmlattrc = xmlnode[i].Attributes;

   //XML Attribute Name and Value returned
   //Example: <Book id = "001">

   Console.Write(xmlattrc[0].Name);
   Console.WriteLine(":\t"+xmlattrc[0].Value);

   //First Child of the XML file - Catalog.xml - returned
   //Example: <Author>Mark</Author>

   Console.Write(xmlnode[i].FirstChild.Name);
   Console.WriteLine(":\t"+xmlnode[i].FirstChild.InnerText);

   //Last Child of the XML file - Catalog.xml - returned
   //Example: <Publisher>Sams</Publisher>

   Console.Write(xmlnode[i].LastChild.Name);
   Console.WriteLine(":\t"+xmlnode[i].LastChild.InnerText);
   Console.WriteLine();

Listing 2 is just an extract from the DisplayCatalog() method of the C# application. It displays the data from the XML file. It uses theXMLNodeList class to retrieve the relevant XML node and then iterates it with the help of the for loop and the Count property of the class. Inside the loop, it creates an instance of the XMLAttributeCollection class and displays the appropriate values using the properties of the class.

Inside the constructor, the code creates an instance of the FileStream class and sets the required permissions (see Listing 3). It then loads the XML document with the help of the XMLDocument class and loads the required instance of the FileStream class with the Load() method of the XMLDocument class.

Listing 3: DisplayCatalog.cs

FileStream fs = new FileStream(path,FileMode.Open,FileAccess.Read,
                               FileShare.ReadWrite);
   xmldoc = new XmlDocument();
   xmldoc.Load(fs);
   DisplayCatalog();

 

The final output looks like the display in Figure 1.

Figure 1: Final Output from Listings 2 and 3

The above walkthrough showed how to display the contents of an XML file using a C# program. The next section demonstrates how to write data directly to the XML file using a C# console application.

Write Data Directly to XML File

Listing 4 appends a new catalog entry to the XML document using the various properties and methods of the XMLDocument class.

Listing 4: AddCatalog.cs

// New XML Element Created
XmlElement newcatalogentry = xmldoc.CreateElement("Book");

// New Attribute Created
XmlAttribute newcatalogattr = xmldoc.CreateAttribute("ID");

// Value given for the new attribute
newcatalogattr.Value = "005";

// Attach the attribute to the XML element
newcatalogentry.SetAttributeNode(newcatalogattr);

// First Element - Book - Created
XmlElement firstelement = xmldoc.CreateElement("Book");

// Value given for the first element
firstelement.InnerText = "Peter";

// Append the newly created element as a child element
newcatalogentry.AppendChild(firstelement);


// Second Element - Publisher - Created
XmlElement secondelement = xmldoc.CreateElement("Publisher");

// Value given for the second element
secondelement.InnerText = "Que Publishing";

// Append the newly created element as a child element
newcatalogentry.AppendChild(secondelement);

// New XML element inserted into the document
xmldoc.DocumentElement.InsertAfter(newcatalogentry,
                                   xmldoc.DocumentElement.LastChild);

// An instance of FileStream class created
// The first parameter is the path to the XML file - Catalog.xml

FileStream fsxml = new FileStream(path,FileMode.Truncate,
                                  FileAccess.Write,
                                  FileShare.ReadWrite);

// XML Document Saved
xmldoc.Save(fsxml);


 
반응형
Posted by blueasa
, |