C# XML(1) 建立/修改/查詢
C# XML(1) 建立/修改/查詢
using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using System.Xml;
namespace
CS_Console_XML
{
class Program
{
static void Pause()
{
Console.Write(“Press any key to continue . . . “);
Console.ReadKey(true);
}
static void Main(string[]
args)
{
//單a純ÂA建O立DsXML檔E案¡Ñ和M寫g入J
/*
//這o是O輸e出DX結g2果G:G
<?xml version=”1.0″
encoding=”utf-8″?>
<AllUsers>
<User RFID=”123456789″>
<USER_IP>192.168.0.1</USER_IP>
<Description>
這o是O描¦y述z</Description>
</User>
</AllUsers>
*/
XmlTextWriter
XTW = new XmlTextWriter(“user.xml”, Encoding.UTF8);
XTW.WriteStartDocument();
XTW.WriteStartElement(“AllUsers”);
XTW.WriteStartElement(“User”);
XTW.WriteAttributeString(“RFID”, “123456789”);
XTW.WriteElementString(“USER_IP”, “192.168.0.1”);
XTW.WriteElementString(“Description”, “這o是O描¦y述z”);
XTW.WriteEndElement();
XTW.WriteEndElement();
XTW.Flush(); //寫g這o行a才~會P|寫g入J檔E案¡Ñ
XTW.Close();
//單a純ÂA讀a取Lu
XmlDocument
xd = new XmlDocument();
xd.Load(“user.xml”);
XmlNode
root = xd.SelectSingleNode(“//User”);
foreach
(XmlElement elm in
root.ChildNodes)
{
Console.WriteLine(elm.Name.Trim()
+
“:” + elm.InnerText.Trim());//Node名W稱U:Node值E
}
//修¡Ñ改±i
XmlDocument
xmlDoc = new XmlDocument();
xmlDoc.Load(“user.xml”);
XmlNode
root1 = xmlDoc.SelectSingleNode(“//User”);
foreach (XmlElement elm in
root1.ChildNodes)
{
elm.InnerText = “123”;
}
//xmlDoc.Save(“user.xml”);//修¡Ñ改±i
xmlDoc.Save(“user1.xml”);//另Dt存s。C
Pause();
}
}
}