溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

C# 讀寫(xiě)XML文件實(shí)例代碼

發(fā)布時(shí)間:2020-09-22 13:33:31 來(lái)源:腳本之家 閱讀:153 作者:OmySql 欄目:編程語(yǔ)言

C#史上最簡(jiǎn)單讀寫(xiě)xml文件方式,創(chuàng)建控制臺(tái)應(yīng)用程序賦值代碼,就可以運(yùn)行,需要改動(dòng),請(qǐng)自行調(diào)整

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace ConsoleApp1
{
  class Program
  {
    public const String xmlPath = "info.xml";

    static void Main(string[] args)
    {

      IDictionary<String, List<String>> infos = new Dictionary<String, List<String>>();

      infos.Add("Evan", new List<string>() { "123", "456" });

      SaveXML(infos);

      ReadXML();
      Console.ReadKey();
    }

    public static void SaveXML(IDictionary<String, List<String>> infos)
    {
      if (infos == null || infos.Count == 0)
      {
        return;
      }

      XmlDocument xmlDoc = new XmlDocument();

      XmlDeclaration dec = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);

      xmlDoc.AppendChild(dec);

      XmlElement _infos = xmlDoc.CreateElement("infos");

      foreach (KeyValuePair<String, List<String>> item in infos)
      {
        XmlElement info = xmlDoc.CreateElement("info");

        XmlElement name = xmlDoc.CreateElement("file1");
        name.InnerText = item.Key;

        info.AppendChild(name);

        XmlNode filelist = xmlDoc.CreateElement("filelist");

        info.AppendChild(filelist);

        foreach (String number in item.Value)
        {
          XmlElement filed = xmlDoc.CreateElement("filed");
          filed.InnerText = number;

          filelist.AppendChild(filed);
        }

        _infos.AppendChild(info);
      }

      xmlDoc.AppendChild(_infos);

      xmlDoc.Save(xmlPath);
    }

    public static IDictionary<String, List<String>> ReadXML()
    {
      IDictionary<String, List<String>> infos = new Dictionary<String, List<String>>();

      if (File.Exists(xmlPath))
      {
        XmlDocument xmlDoc = new XmlDocument();

        xmlDoc.Load(xmlPath);

        XmlNode xn = xmlDoc.SelectSingleNode("infos");

        XmlNodeList xnl = xn.ChildNodes;

        foreach (XmlNode xnf in xnl)
        {
          XmlElement xe = (XmlElement)xnf;

          XmlNode nameNode = xe.SelectSingleNode("file1");

          string name = nameNode.InnerText;
          Console.WriteLine(name);
          XmlNode filelist = xe.SelectSingleNode("filelist");

          List<String> list = new List<string>();

          foreach (XmlNode item in filelist.ChildNodes)
          {
            list.Add(item.InnerText);
          }

          infos.Add(name, list);
        }
      }

      return infos;
    }
  }
}

內(nèi)容擴(kuò)展:

實(shí)例代碼

dim domxmldocument as system.xml.xmldocument 
  dim tmppath as string = apptempfilepath 
  dim xmlfile as string = tmppath + "\testxml.xml" 
 '窗體加載事件 
  private sub testxml_load(byval sender as system.object, byval e as system.eventargs) handles mybase.load 
  '讀xml過(guò)程測(cè)試通過(guò) 
  dim domxmldocument as system.xml.xmldocument 
  dim tmppath as string = apptempfilepath 
  dim xmlfile as string = tmppath + "\testxml.xml" 
  dim reader as system.xml.xmlreader = nothing 
  try 
  reader = new xml.xmltextreader(xmlfile) 
  'reader. 
  while reader.read 
  me.lboxxml.items.add(reader.name + reader.value) 
  end while 
  catch ex as exception 
  msgbox(ex.message) 
  finally 
  if not (reader is nothing) then 
  reader.close() 
  end if 
  end try 
  end sub 
  '載入xml事件 
  private sub btnxmlload_click(byval sender as system.object, byval e as system.eventargs) handles btnxmlload.click 
  'me.lboxxml.items.clear() 
  ''讀xml過(guò)程測(cè)試通過(guò) 
  'dim reader as system.xml.xmlreader = nothing 
  'try 
  ' reader = new xml.xmltextreader(xmlfile) 
  ' while reader.read 
  ' me.lboxxml.items.add(reader.name + ":" + reader.value) 
  ' end while 
  'catch ex as exception 
  ' msgbox(ex.message) 
  'finally 
  ' if not (reader is nothing) then 
  ' reader.close() 
  ' end if 
  'end try 
  dim ds as new dataset 
  try 
  '如果直接使用ds做datasource則不會(huì)展開(kāi)datagrid,用dv則能直接顯示正確。 
  ds.readxml(xmlfile) 
  dim tb as datatable 
  dim dv as dataview 
  tb = ds.tables(0) 
  dv = new dataview(tb) 
  datagrid1.datasource = dv 
  'datagrid1.datamember = "testxmlmember" 
  'datagrid1.datamember = "employeefname" 
  'dim dxd as new xmldatadocument 
  catch ex as exception 
  msgbox(ex.message.tostring) 
  end try 
  end sub 
  '保存新建xml內(nèi)容事件 
  private sub btnsavenew_click(byval sender as system.object, byval e as system.eventargs) handles btnsavenew.click 
  dim mytw as new xmltextwriter(tmppath + "\testxmlwrite.xml", nothing) 
  mytw.writestartdocument() 
  mytw.formatting = formatting.indented 
  mytw.writestartelement("team") 
  mytw.writestartelement("player") 
  mytw.writeattributestring("name", "george zip") 
  mytw.writeattributestring("position", "qb") 
  mytw.writeelementstring("nickname", "zippy") 
  mytw.writeelementstring("jerseynumber", xmlconvert.tostring(7)) 
  mytw.writeendelement() 
  mytw.writeendelement() 
  mytw.writeenddocument() 
  mytw.close() 
  end sub

文件很大的情況下,可以考慮手動(dòng)實(shí)現(xiàn)數(shù)據(jù)更新適配器,比如手動(dòng)實(shí)現(xiàn)一個(gè)xml節(jié)點(diǎn)搜索/更新,這樣就不用重寫(xiě)整個(gè)xml。
如果程序的i/o不是主要問(wèn)題,還是用實(shí)體類整個(gè)的寫(xiě)入更新吧,畢竟數(shù)據(jù)的完整性是第一位的。
如是文章類的,對(duì)該目錄建一個(gè)xml索引文件來(lái)存放文章的編號(hào),url等,用xml的attribute作為標(biāo)記不同字段,內(nèi)容頁(yè)面可以用另外的html或xml頁(yè)面存放,用linq to xml操作數(shù)據(jù),效率不是很差,個(gè)人觀點(diǎn)。當(dāng)搜索時(shí)候只要查詢指定文件名xml或文件類型就可以了。

到此這篇關(guān)于C# 讀寫(xiě)XML文件實(shí)例代碼的文章就介紹到這了,更多相關(guān)C# 讀寫(xiě)XML文件最簡(jiǎn)單方法內(nèi)容請(qǐng)搜索億速云以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持億速云!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI