c\#XML 인 스 턴 스 코드 읽 기

20963 단어 c#xml
XML 파일 은 WinForm 에 있 는 app.config 와 웹 프로그램의 웹.config 파일,그리고 많은 중요 한 장소 에서 자주 사용 되 는 파일 형식 입 니 다.Xml 는 인터넷 환경 에서 플랫폼 을 뛰 어 넘 고 내용 에 의존 하 는 기술 로 현재 구조 화 된 문서 정 보 를 처리 하 는 유력 한 도구 입 니 다.XML 은 간단 한 데이터 저장 언어 로 일련의 간단 한 태그 설명 데 이 터 를 사용 합 니 다.이 표 시 는 편리 한 방식 으로 만 들 수 있 습 니 다.XML 이 사용 하 는 공간 이 바 이 너 리 데이터 보다 더 많은 공간 을 차지 하지만 XML 은 쉽게 파악 하고 사용 할 수 있 습 니 다.마이크로소프트 도 응용 프로그램 에 XML 파일 을 저장 하 는 데 도움 을 주 는 일련의 라 이브 러 리 를 제공 했다.
"프로그램 에서 접근 하여 XML 파일 을 조작 하 는 데 는 일반적으로 두 가지 모델 이 있 는데 그것 이 바로 DOM(문서 대상 모델)과 스 트림 모델 을 사용 하 는 것 이다.DOM 을 사용 하 는 장점 은 XML 문 서 를 편집 하고 업데이트 할 수 있 고 문서 의 데 이 터 를 무 작위 로 방문 할 수 있 으 며 XPath 로 조회 할 수 있다 는 것 이다.그러나 DOM 의 단점 은 전체 문 서 를 메모리 에 한꺼번에 불 러 와 야 한 다 는 것 이다."대형 문서 에 대해 서 는 자원 문 제 를 일 으 킬 수 있다."스 트림 모델 은 이 문 제 를 잘 해결 했다.XML 파일 에 대한 접근 은 스 트림 개념 을 사용 하기 때문이다.즉,언제든지 메모리 에 현재 노드 만 있 지만 부족 한 점도 있다.읽 기 전용 이 고 앞으로 만 있 으 며 문서 에서 뒤로 내 비게 이 션 을 수행 할 수 없다."
다음은 XML 파일 을 자주 읽 는 세 가지 방법 을 소개 하 겠 습 니 다.각각 
1:XmlDocument 사용
2:XmlTextReader 사용 하기
3:Linq to Xml 사용
여기 서 제 가 먼저 XML 파일 을 만 들 겠 습 니 다.북 xml 라 는 이름 아래 의 모든 방법 은 이 XML 파일 을 기반 으로 합 니 다.파일 내용 은 다음 과 같 습 니 다.

 <?xml version="1.0" encoding="utf-8"?>
   <bookstore>
    <!--       -->
    <book Type="   " ISBN="7-111-19149-2">
     <title>    </title>
     <author>   </author>
     <price>30.00</price>
    </book>
    <book Type="   " ISBN="7-111-19149-3">
    <title>            </title>
    <author>   </author>
    <price>27.00</price>
   </book>
   <book Type="   " ISBN="7-111-19149-4">
    <title>         </title>
    <author>   </author>
    <price>25.00</price>
   </book>
   <book Type="   " ISBN="7-111-19149-5">
    <title>         </title>
    <author>   </author>
    <price>39.00</price>
   </book>
   <book Type="   " ISBN="7-111-19149-6">
    <title>       </title>
    <author>   </author>
    <price>23.00</price>
   </book>
   <book Type="   " ISBN="7-111-19149-1">
    <title>       </title>
    <author>7-111-19149-1</author>
    <price>28</price>
   </book>
  </bookstore>
읽 기 편 하도록 책의 실체 클래스 를 정 의 했 습 니 다.북 모델 이 라 고 하 는데 구체 적 인 내용 은 다음 과 같 습 니 다.

 using System;
   using System.Collections.Generic;
   using System.Linq;
   using System.Text;
   
   namespace   XmlDocument
   {
     public class BookModel
     {
      public BookModel()
      { }
      /// <summary>
      ///         
      /// </summary>
      private string bookType;
   
      public string BookType
      {
        get { return bookType; }
        set { bookType = value; }
      }
   
      /// <summary>
      ///      ISBN 
      /// </summary>
      private string bookISBN;
   
      public string BookISBN
      {
        get { return bookISBN; }
        set { bookISBN = value; }
      }
   
      /// <summary>
      ///   
      /// </summary>
      private string bookName;
   
      public string BookName
      {
        get { return bookName; }
        set { bookName = value; }
      }
   
      /// <summary>
      ///   
      /// </summary>
      private string bookAuthor;
   
      public string BookAuthor
      {
        get { return bookAuthor; }
        set { bookAuthor = value; }
      }
   
      /// <summary>
      ///   
      /// </summary>
      private double bookPrice;
   
      public double BookPrice
      {
        get { return bookPrice; }
        set { bookPrice = value; }
      }
    }
  }

1.XmlDocument 사용 하기.
XmlDocument 를 사용 하 는 것 은 문서 구조 모델 을 기반 으로 XML 파일 을 읽 는 방식 입 니 다.XML 파일 에서 우 리 는 XML 을 문서 성명(Declare),요소(Element),속성(Attribute),텍스트(Text)등 으로 구 성 된 트 리 로 볼 수 있 습 니 다.처음에 하나의 결점 을 뿌리 결점 이 라 고 부 르 고 모든 결점 은 자신의 하위 결점 이 있 습 니 다.결점 을 얻 은 후,일련의 속성 이나 방법 을 통 해 이 결점 의 값 이나 다른 속성 을 얻 을 수 있 습 니 다.예 를 들 어:

  xn       
   xn.Name;//       
   xn.Value;//      
   xn.ChildNodes;//          
   xn.ParentNode;//        
   .......
1.1 모든 데 이 터 를 읽 습 니 다.
사용 할 때 먼저 XmlDocument 대상 을 설명 한 다음 Load 방법 을 사용 하여 지정 한 경로 에서 XML 파일 을 불 러 옵 니 다.

XmlDocument doc = new XmlDocument();
doc.Load(@"..\..\Book.xml");
그리고 SelectSingleNode 를 호출 하여 지정 한 노드 를 얻 을 수 있 으 며,GetAttribute 를 통 해 구체 적 인 속성 값 을 얻 을 수 있 습 니 다.아래 코드 를 참조 하 십시오.

  //      bookstore
   XmlNode xn = xmlDoc.SelectSingleNode("bookstore");
   
   
   //            
   XmlNodeList xnl = xn.ChildNodes;
   
   foreach (XmlNode xn1 in xnl)
   {
    BookModel bookModel = new BookModel();
    //         ,          
    XmlElement xe = (XmlElement)xn1;
    //   Type ISBN        
    bookModel.BookISBN = xe.GetAttribute("ISBN").ToString();
    bookModel.BookType = xe.GetAttribute("Type").ToString();
    //   Book        
    XmlNodeList xnl0 = xe.ChildNodes;
    bookModel.BookName=xnl0.Item(0).InnerText;
    bookModel.BookAuthor=xnl0.Item(1).InnerText;
    bookModel.BookPrice=Convert.ToDouble(xnl0.Item(2).InnerText);
    bookModeList.Add(bookModel);
  }
  dgvBookInfo.DataSource = bookModeList;

정상 적 인 상황 에서 위의 코드 는 아무런 문제 가 없 는 것 같 지만 위의 XML 파일 을 읽 는 데 오류 가 발생 할 수 있 습 니 다.그 이 유 는 제 위의 XML 파일 에 주석 이 있 기 때 문 입 니 다.여러분 은 북 xml 파일 의 세 번 째 줄 을 참조 하 셔 도 됩 니 다.제 가 마음대로 추가 한 주석 입 니 다.주석 도 하나의 결점 형식 입 니 다.특별한 설명 이 없 는 상황 에서기본적으로 노드(Node)이기 도 합 니 다.따라서 노드 를 요소 로 변환 할 때 오류 가 발생 합 니 다."System.Xml.XmlComment"형식의 대상 을"System.Xml.XmlElement"형식 으로 강제로 변환 할 수 없습니다."

다행히 그 안에 해결 방법 이 있 습 니 다.그것 은 바로 읽 을 때 컴 파일 러 에 게 안의 주석 정 보 를 무시 하 라 고 알려 주 는 것 입 니 다.수정 은 다음 과 같 습 니 다.

XmlDocument xmlDoc = new XmlDocument();
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;//         
XmlReader reader = XmlReader.Create(@"..\..\Book.xml", settings);
xmlDoc.Load(reader);
마지막 으로 읽 은 후에 reader 를 끄 는 것 을 기억 하 세 요.

 reader.Close();
이렇게 하면 그것 은 오류 가 발생 하지 않 을 것 이다.
마지막 실행 결 과 는 다음 과 같 습 니 다.

1.2 책 한 권 의 정 보 를 추가 합 니 다.
파일 에 새 데 이 터 를 추가 할 때 는 먼저 XmlDocument 을 통 해 전체 문 서 를 불 러 온 다음 SelectSingleNode 방법 으로 루트 노드 를 얻 습 니 다.CreateElement 방법 으로 요 소 를 만 들 고 CreateAttribute 로 속성 을 만 듭 니 다.AppendChild 로 현재 노드 를 다른 노드 에 연결 하고 SetAttributeNode 로 노드 의 속성 을 설정 합 니 다.구체 적 인 코드 는 다음 과 같 습 니 다.
파일 을 불 러 오고 노드 를 선택 하 십시오:

XmlDocument doc = new XmlDocument();
doc.Load(@"..\..\Book.xml");
XmlNode root = doc.SelectSingleNode("bookstore");
노드 를 만 들 고 노드 의 속성 을 설정 합 니 다:

  XmlElement xelKey = doc.CreateElement("book");
   XmlAttribute xelType = doc.CreateAttribute("Type");
   xelType.InnerText = "adfdsf";
   xelKey.SetAttributeNode(xelType);
하위 노드 만 들 기:

  XmlElement xelAuthor = doc.CreateElement("author");
   xelAuthor.InnerText = "dfdsa";
   xelKey.AppendChild(xelAuthor);
마지막 으로 북 노드 를 노드 에 연결 하고 전체 파일 을 저장 합 니 다.

root.AppendChild(xelKey);
doc.Save(@"..\..\Book.xml");
위의 방법 으로 기 존 파일 에 데 이 터 를 추가 하 는 것 입 니 다.기 존 데 이 터 를 모두 덮어 쓰 려 면 변경 할 수 있 습 니 다.LoadXml 방법 을 사용 하 십시오.

  XmlDocument doc = new XmlDocument();
   doc.LoadXml("<bookstore></bookstore>");//    ,            ,        
루트 노드 를 직접 선택 하 였 습 니 다.그 다음 에는 selectSingleNode 방법 으로 루트 노드 를 선택 하지 않 고 바로 노드 를 만 들 면 됩 니 다.코드 가 같 습 니 다.
1.3 데이터 삭제
어떤 결점 을 삭제 하려 면 아버지의 결점 을 직접 찾 은 다음 Remove Child 방법 을 사용 하면 됩 니 다.현재 관건 적 인 문 제 는 이 결점 을 어떻게 찾 느 냐 하 는 것 입 니 다.위의 SelectSingleNode 는 Xpath 표 에 들 어 갈 수 있 습 니 다.우 리 는 책의 ISBN 번 호 를 통 해 이 책 이 있 는 결점 을 찾 을 수 있 습 니 다.다음 과 같 습 니 다.

 XmlElement xe = xmlDoc.DocumentElement; // DocumentElement   xml      XmlElement.
   string strPath = string.Format("/bookstore/book[@ISBN=\"{0}\"]", dgvBookInfo.CurrentRow.Cells[1].Value.ToString());
   XmlElement selectXe = (XmlElement)xe.SelectSingleNode(strPath); //selectSingleNode   XPath   ,            .
   selectXe.ParentNode.RemoveChild(selectXe);
"/bookstore/book[@ISBN=\"{0}\"]"은 Xpath 표현 식 입 니 다.ISBN 번호 가 선택 한 줄 의 ISBN 번호 인 책 을 찾 았 습 니 다.Xpath 에 관 한 지식 은 참고 하 십시오:XPath 문법
1.4 특정한 중요 한 데 이 터 를 수정 합 니 다.
어떤 데 이 터 를 수정 하면 먼저 Xpath 표현 식 으로 수정 해 야 할 결점 을 찾 은 다음 에 요소 라면 이 요소 에 직접 값 을 부여 합 니 다.속성 이 라면 SetAttribute 방법 으로 설정 하면 됩 니 다.다음 과 같 습 니 다.

  XmlElement xe = xmlDoc.DocumentElement; // DocumentElement   xml      XmlElement.
   string strPath = string.Format("/bookstore/book[@ISBN=\"{0}\"]", dgvBookInfo.CurrentRow.Cells[1].Value.ToString());
   XmlElement selectXe = (XmlElement)xe.SelectSingleNode(strPath); //selectSingleNode   XPath   ,            .
   selectXe.SetAttribute("Type", dgvBookInfo.CurrentRow.Cells[0].Value.ToString());//     SetAttribute       
   selectXe.GetElementsByTagName("title").Item(0).InnerText = dgvBookInfo.CurrentRow.Cells[2].Value.ToString();
   selectXe.GetElementsByTagName("author").Item(0).InnerText = dgvBookInfo.CurrentRow.Cells[3].Value.ToString();
   selectXe.GetElementsByTagName("price").Item(0).InnerText = dgvBookInfo.CurrentRow.Cells[4].Value.ToString();
   xmlDoc.Save(@"..\..\Book.xml");
2.XmlTextReader 와 XmlTextWriter 사용 하기
XmlTextReader 와 XmlTextWriter 는 스 트림 형식 으로 XML 파일 을 읽 고 씁 니 다.
2.1XmlTextReader
XmlTextReader 를 사용 하여 데 이 터 를 읽 을 때 먼저 스 트림 을 만 든 다음 read()방법 으로 계속 아래로 읽 고 읽 은 노드 의 유형 에 따라 해당 하 는 동작 을 합 니 다.다음 과 같 습 니 다.
   

 XmlTextReader reader = new XmlTextReader(@"..\..\Book.xml");
        List<BookModel> modelList = new List<BookModel>();
        BookModel model = new BookModel();
        while (reader.Read())
        {
          
          if (reader.NodeType == XmlNodeType.Element)
          {
            if (reader.Name == "book")
            {
              model.BookType = reader.GetAttribute(0);
              model.BookISBN = reader.GetAttribute(1);
            }
            if (reader.Name == "title")
            {
              model.BookName=reader.ReadElementString().Trim();
            }
            if (reader.Name == "author")
            {
              model.BookAuthor = reader.ReadElementString().Trim();
            }
            if (reader.Name == "price")
            {
              model.BookPrice = Convert.ToDouble(reader.ReadElementString().Trim());
            }
          }
   
          if (reader.NodeType == XmlNodeType.EndElement)
          {
            modelList.Add(model);
            model = new BookModel();
          }
   
          
        }
        modelList.RemoveAt(modelList.Count-1);
        this.dgvBookInfo.DataSource = modelList;
중요 한 것 은 속성 을 읽 을 때 어떤 결점 이 몇 가지 속성 을 가지 고 있 는 지 알 고 GetAttribute 방법 으로 읽 는 것 입 니 다.속성 을 읽 을 때 다른 방법 도 사용 할 수 있 습 니 다.바로 MoveToAttribute 방법 입 니 다.아래 코드 를 참조 할 수 있 습 니 다.

  if (reader.Name == "book")
     {
       for (int i = 0; i < reader.AttributeCount; i++)
       {
         reader.MoveToAttribute(i);
         string str = "  :" + reader.Name + "=" + reader.Value;
       }
       model.BookType = reader.GetAttribute(0);
       model.BookISBN = reader.GetAttribute(1);
    }
효 과 는 다음 과 같 습 니 다:

2.2XmlTextWriter
XmlTextWriter 가 파일 을 쓸 때 기본 값 은 이전 파일 을 덮어 쓰 는 것 입 니 다.이 파일 이름 이 존재 하지 않 으 면 이 파일 을 만 듭 니 다.먼저 만 들 XML 파일 형식 을 설정 합 니 다.

 XmlTextWriter myXmlTextWriter = new XmlTextWriter(@"..\..\Book1.xml", null);
   //   Formatting         XML        。   ,           Indentation   IndentChar      。
   myXmlTextWriter.Formatting = Formatting.Indented;
그 다음 에 Write StartElement 와 Write Element String 방법 으로 요 소 를 만 들 수 있 습 니 다.이 두 가지 차이 점 은 하위 노드 의 요소 가 있 으 면 만 들 때 Write StartElement 을 사용 한 다음 에 하위 요 소 를 만 들 고 만 든 후에 해당 하 는 Write EndElement 를 호출 하여 컴 파일 러 에 알려 주 고 만 들 었 습 니 다.Write Element String 으로 하나의 요 소 를 만 듭 니 다.Write AttributeString 으로 속성 을 만 듭 니 다.다음 과 같 습 니 다.

  XmlTextWriter myXmlTextWriter = new XmlTextWriter(@"..\..\Book1.xml", null);
        //   Formatting         XML        。   ,           Indentation   IndentChar      。
        myXmlTextWriter.Formatting = Formatting.Indented;
   
        myXmlTextWriter.WriteStartDocument(false);
        myXmlTextWriter.WriteStartElement("bookstore");
   
        myXmlTextWriter.WriteComment("       ");
        myXmlTextWriter.WriteStartElement("book");
   
        myXmlTextWriter.WriteAttributeString("Type", "   ");
        myXmlTextWriter.WriteAttributeString("ISBN", "111111111");
   
        myXmlTextWriter.WriteElementString("author","  ");
        myXmlTextWriter.WriteElementString("title", "      ");
        myXmlTextWriter.WriteElementString("price", "16.00");
   
        myXmlTextWriter.WriteEndElement();
        myXmlTextWriter.WriteEndElement();
   
        myXmlTextWriter.Flush();
        myXmlTextWriter.Close();

3.Linq to XML 을 사용 합 니 다.
Linq 는 C\#3.0 에 나타 난 새로운 기능 입 니 다.이 를 사용 하면 많은 데이터 원본 을 편리 하 게 조작 할 수 있 고 XML 파일 도 포함 합 니 다.Linq 를 사용 하여 XML 파일 을 조작 하 는 것 이 매우 편리 하고 간단 합 니 다.다음은 코드 를 직접 보 겠 습 니 다.
검색 한 데 이 터 를 표시 하 는 방법 을 먼저 정의 합 니 다.

  private void showInfoByElements(IEnumerable<XElement> elements)
      {
        List<BookModel> modelList = new List<BookModel>();
        foreach (var ele in elements)
        {
          BookModel model = new BookModel();
          model.BookAuthor = ele.Element("author").Value;
          model.BookName = ele.Element("title").Value;
          model.BookPrice = Convert.ToDouble(ele.Element("price").Value);
          model.BookISBN=ele.Attribute("ISBN").Value;
          model.BookType=ele.Attribute("Type").Value;
          
          modelList.Add(model);
        }
        dgvBookInfo.DataSource = modelList;
      }
3.1 모든 데이터 읽 기
책 이라는 요소 의 이 결점 을 직접 찾 은 다음 모든 결 과 를 읽 습 니 다.

  private void btnReadAll_Click(object sender, EventArgs e)
      {
        XElement xe = XElement.Load(@"..\..\Book.xml");
        IEnumerable<XElement> elements = from ele in xe.Elements("book")
                         select ele;
        showInfoByElements(elements);
      }
3.2 데이터 삽입
노드 와 속성 을 삽입 하 는 것 은 모두 new 방법 을 사용 합 니 다.다음 과 같 습 니 다.

  private void btnInsert_Click(object sender, EventArgs e)
       {
         XElement xe = XElement.Load(@"..\..\Book.xml");
         XElement record = new XElement(
         new XElement("book",
         new XAttribute("Type", "   "),
         new XAttribute("ISBN","7-111-19149-1"),
         new XElement("title", "       "),
         new XElement("author", "7-111-19149-1"),
        new XElement("price", 28.00)));
        xe.Add(record);
        xe.Save(@"..\..\Book.xml");
        MessageBox.Show("    !");
        btnReadAll_Click(sender, e);
      }
3.3 선택 한 데이터 삭제
먼저 선 택 된 줄 을 ISBN 번 호 를 통 해 이 요 소 를 찾 은 다음 Remove 방법 으로 직접 삭제 합 니 다.다음 과 같 습 니 다.

  private void btnDelete_Click(object sender, EventArgs e)
      {
        if (dgvBookInfo.CurrentRow != null)
        {
          //dgvBookInfo.CurrentRow.Cells[1]   ISBN 
          string id = dgvBookInfo.CurrentRow.Cells[1].Value.ToString();
          XElement xe = XElement.Load(@"..\..\Book.xml");
          IEnumerable<XElement> elements = from ele in xe.Elements("book")
                           where (string)ele.Attribute("ISBN") == id
                          select ele;
         {
          if (elements.Count() > 0)
            elements.First().Remove();
          }
          xe.Save(@"..\..\Book.xml");
          MessageBox.Show("    !");
          btnReadAll_Click(sender, e);
   
        }
      }
3.4 모든 데이터 삭제
위의 것 과 유사 하 게 모든 데 이 터 를 선택 한 다음 Remove 방법 으로 다음 과 같 습 니 다.

  private void btnDeleteAll_Click(object sender, EventArgs e)
      {
        XElement xe = XElement.Load(@"..\..\Book.xml");
        IEnumerable<XElement> elements = from ele in xe.Elements("book")
                         select ele;
        if (elements.Count() > 0)
        {
          elements.Remove();
        }
        xe.Save(@"..\..\Book.xml");
        MessageBox.Show("    !");
        btnReadAll_Click(sender, e);
      }
3.5 특정한 기록 수정
먼저 수정 할 결점 을 얻 은 다음,SetAttributeValue 로 속성 을 수정 하고,ReplaceNodes 로 결점 요 소 를 수정 합 니 다.다음 과 같다.

  private void btnSave_Click(object sender, EventArgs e)
   {
     XElement xe = XElement.Load(@"..\..\Book.xml");
     if (dgvBookInfo.CurrentRow != null)
     {
       //dgvBookInfo.CurrentRow.Cells[1]   ISBN 
       string id = dgvBookInfo.CurrentRow.Cells[1].Value.ToString();
       IEnumerable<XElement> element = from ele in xe.Elements("book")
                       where ele.Attribute("ISBN").Value == id
                      select ele;
      if (element.Count() > 0)
      {
        XElement first = element.First();
        ///      
        first.SetAttributeValue("Type", dgvBookInfo.CurrentRow.Cells[0].Value.ToString());
        ///      
        first.ReplaceNodes(
             new XElement("title", dgvBookInfo.CurrentRow.Cells[2].Value.ToString()), 
             new XElement("author", dgvBookInfo.CurrentRow.Cells[3].Value.ToString()),
             new XElement("price", (double)dgvBookInfo.CurrentRow.Cells[4].Value) 
             );
      }
      xe.Save(@"..\..\Book.xml");
   
      MessageBox.Show("    !");
      btnReadAll_Click(sender, e);
    }
  }
최종 효 과 는 다음 과 같다.

이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기