shepherd's Blog

[C#] XML 본문

.NET

[C#] XML

shepherd.dev 2015. 7. 30. 20:48

[C#] XML


1. System.Xml Library 사용


using System.Xml;


void Main(string[] args)

{

// XmlDocument 생성

XmlDocument xmldoc = new XmlDocument();

// Root Node 생성 후 XML Doc에 붙이기

XmlNode rootnode = xmldoc.CreateElement("", "Root", "");

xmldoc.AppendChild(rootnode);

// Xml File Save

xmldoc.Save("filepath");

// Xml File Load

xmldoc.Load("filepath");

// Root Node의 첫번째 Element 생성 

XmlElement Node1 = xmldoc.CreateElement("Node1");

// Root Node의 첫번째 Element의 첫번째 자식 생성 후 attribute와 내용 삽입

XmlElement Node11 = xmldoc.CreateElement("Node1-1");

Node11.SetAttribute("attribute", "Node1-1");

Node11.InnerText = "Node1-1";

// Root Node의 첫번째 Element의 두번째 자식 생성 후 내용 삽입

XmlElement Node12 = xmldoc.CreateElement("Node1-2");

Node12.InnerText = "Node1-2";

// 각 Element들을 부모에게 삽입

Node1.AppendChild(Node11);

Node1.AppendChild(Node12);

rootnode.AppendChild(Node1);

// Root Node의 두번째 Element 생성

XmlElement Node2 = xmldoc.CreateElement("Node2");

Node2.InnerText = "Node2";

rootnode.AppendChild(Node2);

// Root Node의 세번째 Element 생성

XmlElement Node3 = xmldoc.CreateElement("Node3");

Node3.InnerText = "Node3";

rootnode.AppendChild(Node3);

// 저장

xmldoc.Save("filepath");

}


2. Linq 사용


using System.Xml.Linq;

void Main(string[] args)

{

// XDocument를 통해 XML Document 생성

XDocument xmldoc = new XDocument();

// XElement를 통해 XML 생성

XElement doc = new XElement("Root",

new XElement("Node1",

new XElement("Node1-1", "Root1-1"),

new XElement("Node1-2", "Root1-2")),

new XElement("Node2", "Root2")

);

// Node 추가

doc.Add("Node3","Root3");

// Elment를 Document에 삽입

xmldoc.Add(doc);

// 파일로 저장

xmldoc.Save("filepath");

}



using System.Xml.Linq;

void Main(string[] args)

{

XElement xmldoc = new XElement("Root",

new XElement("Node1",

new XElement("Node1-1", "Root1-1"),

new XElement("Node1-2", "Root1-2")),

new XElement("Node2", "Root2"),

new XElement("Node3", "Root3")

);

// 파일로 저장

xmldoc.Save("filepath");

}


 두 가지 모두 결과는 다음과 같습니다. Linq를 사용할 경우 좀 더 간단하게 사용할 수 있습니다. Document에 Element를 추가하지 않고 Element로만 처리해도 결과는 같습니다. Document 속성을 변경할 필요가 있을 경우 XDocument를 사용하면 됩니다.


-결과


<?xml version="1.0" encoding="urf-8"?>

<Root>

  <Node1>

    <Node1-1 attribute="Node1-1">Node1-1</Node1-1>

    <Node1-2>Node1-2</Node1-2>

  </Node1>

  <Node2>Node2</Node2>

  <Node3>Node3</Node3>

</Root>




'.NET' 카테고리의 다른 글

[C++/CLI] C# C++ 연동  (0) 2015.08.04