class DomGeneration
{
// 해당 객체 전역에 사용하기 위해
XmlDocument doc;
XmlElement root;
DomGeneration()
{
try
{
// Dom 객체를 생성해서
doc = new XmlDocument();
// XML 파일을 로딩
doc.Load("book.xml");
// Root Element를 지정
root = doc.DocumentElement;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
/// <summary>
/// Root Element 명 출력
/// </summary>
public void GetRoot()
{
Console.WriteLine("루트 엘리먼트 : {0}", root.Name);
}
/// <summary>
/// 입력, 수정, 삭제된 내용을 Xml파일로 저장
/// </summary>
public void Save()
{
XmlTextWriter writer = new XmlTextWriter("book.xml", Encoding.UTF8);
//들여쓰기 지정
writer.Formatting = Formatting.Indented;
doc.WriteTo(writer);
writer.Flush();
Console.WriteLine("Xml 을 저장하셨습니다");
}
/// <summary>
/// 3번째 도서명의 저자 출력
/// </summary>
public void GetChild()
{
string authorValue;
// XPath 를 이용(혹, 없다면 예외처리해야 함)
// XmlNodeList writer = root.SelectNodes("//도서[3]/저자");
// authorValue = writer.Item(0).FirstChild.Value;
XmlNodeList nodelist = root.ChildNodes;
XmlNode book3 = nodelist.Item(2);
XmlElement author = (XmlElement)book3.ChildNodes.Item(1);
authorValue = author.FirstChild.Value;
Console.WriteLine("세번째 : " + authorValue);
}
/// <summary>
/// 1번째 도서의 ISBN Attribute를 출력
/// </summary>
public void GetAttribute()
{
XmlElement book = (XmlElement) root.FirstChild;
string attr = book.GetAttribute("ISBN");
Console.WriteLine("ISBN=" + attr);
XmlAttribute isbn = (XmlAttribute)book.Attributes.GetNamedItem("ISBN");
string isbnvalue = isbn.Value;
Console.WriteLine("ISBN = " + isbnvalue);
}
/// <summary>
/// book 노드의 자식 Element명과 Text 값 출력
/// </summary>
public void GetElements(XmlNode book)
{
XmlNodeList elements = book.ChildNodes;
int elementcnt = elements.Count;
// 아래 GetAttributes()처럼 foreach문 사용가능
for(int i = 0;i < elementcnt;i++)
{
XmlElement child= (XmlElement)elements.Item(i);
Console.WriteLine("\t{0}:{1}",child.Name, child.FirstChild.Value);
}
}
/// <summary>
/// book 노드의 자식 Attribute명과 값 출력
/// </summary>
public void GetAttributes(XmlNode book)
{
XmlNamedNodeMap attrs = book.Attributes;
// XmlAttributeCollection attrs = book.Attributes;
foreach(XmlAttribute attr in attrs)
Console.WriteLine("\t{0}:{1}", attr.Name, attr.Value);
}
/// <summary>
/// 도서 속성 값에 따라 도서 Element 삭제
/// </summary>
/// <param name="item_number">삭제할 Element의 번호속성 값</param>
public void RemoveChild(int item_number)
{
try
{
// 삭제할 Element를 구함
XmlNode node = root.SelectSingleNode("//도서[@번호='" + item_number + "']");
// Element삭제
root.RemoveChild(node);
// 문서저장하기 위해 메서드 호출
Save();
}
// 삭제할 노드가 존재하지 않을 경우 예외부분
catch(NullReferenceException)
{
Console.WriteLine("삭제할 놈이 없다.");
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
/// <summary>
/// 도서 속성 값에 따라 도서 Element 삭제
/// </summary>
/// <param name="num">삭제할 Element의 번호속성 값</param>
public void DeleteElem2(string num)
{
XmlNodeList booklist=root.ChildNodes;
bool flag = true; // 삭제하고자 하는 속성 값 존재 여부
for(int i=0 ; i<booklist.Count ; i++)
{
//GetAttribute를 사용하기위한 형변환
string bunho=((XmlElement)booklist.Item(i)).GetAttribute("번호");
if(bunho==num)
{
root.RemoveChild(booklist.Item(i));
flag=false;
Save();
break;
}
}
if(flag)
Console.WriteLine("삭제할 도서가 없다");
}
public void CreateXml()
{
XmlDocument xmlDoc=new XmlDocument();
}
/// <summary>
/// Element 추가
/// </summary>
public void AppendChildElem(string bookname,string author,string isbn)
{
if(root.HasChildNodes)
{// root에 자식 Element가 존재한다면 마지막 자식 Element를 복사해서
// Element 값과 Attribute 값 변경
XmlNode copynode=root.LastChild.CloneNode(true);
copynode.FirstChild.FirstChild.Value=bookname;
copynode.ChildNodes.Item(1).FirstChild.Value=author;
string num =copynode.Attributes.GetNamedItem("번호").Value;
int bunho=int.Parse(num)+1;
((XmlElement)copynode).SetAttribute("ISBN",isbn);
((XmlElement)copynode).SetAttribute("번호",bunho.ToString());
root.AppendChild(copynode);
XmlSave();
}
else
{// 존재하지 않는다면 Element과 Attribute를 생성
XmlElement newbook=doc.CreateElement("도서");
XmlElement newbookname=doc.CreateElement("도서명");
newbookname.Value=bookname;
XmlElement newauthor=doc.CreateElement("저자");
//XmlText booknametxt=doc.CreateTextNode(bookname);
XmlText authortxt=doc.CreateTextNode(author);
newbook.SetAttribute("ISBN",isbn);
//newbookname.AppendChild(booknametxt);
newauthor.AppendChild(authortxt);
newbook.AppendChild(newbookname);
newbook.AppendChild(newauthor);
root.AppendChild(newbook);
Save();
}
}
static void Main(string[] args)
{
DomGeneration doc = new DomGeneration();
doc.Insert();
// XmlNodeList booklist = doc.root.ChildNodes;
// int bookcnt = booklist.Count;
// for(int i=0; i<bookcnt; i++)
// {
// Console.WriteLine("{0}번째 도서 목록",i+1);
// XmlNode book = booklist.Item(i);
// doc.GetAttributes(book);
// doc.GetElements(book);
}
}
}
}
'.NET' 카테고리의 다른 글
ASP.NET 웹 응용 프로그램의 페이지 및 응용 프로그램 컨텍스트 (2) | 2007.08.22 |
---|---|
component ; 컴포넌트 (0) | 2007.08.21 |
XmlDocument (DOM) 객체를 이용한 예제 (2) | 2007.08.20 |
XML DOM(문서 개체 모델) (0) | 2007.08.20 |
Ajax와 DOM이용해서 웹 구현 2 (3) | 2007.08.20 |
Ajax와 DOM이용해서 웹 구현 1 (0) | 2007.08.20 |
많은 감사 우수한 위치! 나는 너의 웹사이트를 사랑한다!
걸출한 디자인! 좋은 디자인.