C#操作XML文件

XML(可扩展标记语言)基于文本编码,用于Web上数据交换和存储,比起数据库来说更加灵活,更加方便,读写不用什么数据库驱动,编写方法也很简单,不用什么软件直接用记事本就可以搞定了。

对学编程的人员来说,XML是必学的技术之一。因此,这些天我都在研究C#中对XML的读写,感觉所用到的操作特别多,设计到的方法和类也比较多(反正看的时候有点晕晕的,可以看懂,但要常应用加深印象)。

所用到的操作类都在System.Xml命名空间里面,因此程序设计开始的时候必须先引用这个命名空间。

 

 

//生成XML文件

const string fpath = "root.xml";

XmlDocument xd = new XmlDocument();

xd.LoadXml("<?xml version='1.0' encoding='utf-8'?>" + "<root><para>some para text</para></root>");

xd.Save(fpath);

 

结果是在程序目录下生成名为root.xml文件

内容如下:

<?xml version='1.0' encoding='utf-8'?>

<root>

<para>some para text</para>

</root>

 

 

//添加节点

XmlDocument xd = new XmlDocument();

xd.Load("sample.xml");

XmlDocumentFragment xdf = xd.CreateDocumentFragment();

XmlElement xe = xd.CreateElement("test", "Product", "uri:test"); //新建元素

XmlAttribute xa = xd.CreateAttribute("ProductID"); //新建属性

xa.Value = "MU98";  //属性值

xe.Attributes.SetNamedItem(xa);   //挂到xe元素上去

XmlElement newxa = xd.CreateElement("color");

newxa.InnerText = "green";  //元素值

xe.AppendChild(newxa);  //成为xe子节点

XmlElement newsize = xd.CreateElement("size");

newsize.InnerText = "P";

xe.AppendChild(newsize);

XmlElement newpri = xd.CreateElement("price");

newpri.InnerText = "55.99";

xe.AppendChild(newpri);

xdf.AppendChild(xe);

XmlElement newxe = (XmlElement)xd.SelectSingleNode("//ProductFamily");  //匹配XPATH表达式第一个XMLNodes节点

newxe.AppendChild(xdf.FirstChild);

 

//修改节点

XmlDocument xd = new XmlDocument();

xd.Load("sample.xml");

XmlNodeList xnl = xd.SelectNodes("//price");

foreach (XmlNode xn in xnl)

{

     xn.InnerXml = "<currency type='dollar'>" + xn.InnerText + "</currency>";

}

 

原来:

<price>129.55</price>

结果:

<price><currency type="dollar">129.55</currency></price>

 

 

//删除节点

XmlDocument xd = new XmlDocument();

xd.Load("sample.xml");

XmlNodeList xnl = xd.GetElementsByTagName("Company");

foreach (XmlNode xn in xnl)

{

     XmlNodeList xProlist=xn.SelectNodes("ProductFamily");

     foreach (XmlNode xn1 in xProlist)

     {

        xn.RemoveChild(xn1);

     }

}

 

原来:

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

<Catalog xmlns:test="uri:test">

  <Company email="celtic@deltabis.net" name="Celtic Productions">

    <ProductFamily familyID="pftops" LastUpdate="2008-03-22" buyersURI="http://www.deltabis.com/buyers/tops">

      <test:Product ProductID="MU78">

        <color>red</color>

        <size>M</size>

        <price>129.55</price>

      </test:Product>

    </ProductFamily>

  </Company>

</Catalog>

 

 

结果:

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

<Catalog xmlns:test="uri:test">

<Company email="celtic@deltabis.net" name="Celtic Productions">

</Company>

</Catalog>

 

 

 

 

//更新操作

public void Update()

{

   XmlDocument xd = new XmlDocument();

   xd.Load("XMLFile.xml");

   XmlNodeList xnl = xd.SelectSingleNode("bookstore").ChildNodes;

   foreach (XmlNode xn in xnl)

   {

        XmlElement xe = (XmlElement)xn;

        if (xe.GetAttribute("genre") == "李赞红")

        {

            xe.SetAttribute("genre", "Update李赞红");

            XmlNodeList xnl1 = xe.ChildNodes;

            foreach (XmlNode xn1 in xnl1)

            {

               XmlElement xe1 = (XmlElement)xn1;

               if (xe1.Name == "author")

               {

                   xe1.InnerText = "小赖";

                   break;

                }

             }

             break;

           }              

    }

     xd.Save("XMLFile.xml");

     System.Diagnostics.Process.Start("XMLFile.xml");

     Console.ReadKey();

}

 

 

大体操作就这些了。

当然,XML还有很多应用,我现在学习的只是冰山一角,今后还要多多深入。

C#XML入门经典-C#编程人员必备的XML技能》这本书确实很不错,虽然很多地方说得很杂很乱,但认真拜读也不失为一本好书,嗯~~加油,多看几遍……

原文地址:https://www.cnblogs.com/saper/p/1316411.html