C#操作xml文件

//创建xml文件(添加根节点的属性)

StreamWriter sw = File.CreateText(AppDomain.CurrentDomain.BaseDirectory + "Xml\\" + xmlFilename + ".xml");

sw.WriteLine("<?xml version='1.0' encoding='utf-8' ?>");

sw.WriteLine("<media></media>");

sw.Close();

XmlDocument doc = new XmlDocument();

doc.Load(AppDomain.CurrentDomain.BaseDirectory + "Xml\\" + xmlFilename + ".xml");

XmlNode nodePath = doc.SelectSingleNode("//media");

if (!(nodePath == null))

{

      XmlNode titleAttribute;

      titleAttribute = doc.CreateAttribute("title");

      titleAttribute.Value = TextBox1.Text;

      nodePath.Attributes.SetNamedItem(titleAttribute);

       XmlNode imgAttribute;

       imgAttribute = doc.CreateAttribute("imagesUrl");

       imgAttribute.Value = "~/images/parent.gif";

       nodePath.Attributes.SetNamedItem(imgAttribute);

       RootTitle = TextBox1.Text;

 }

doc.Save(AppDomain.CurrentDomain.BaseDirectory + "Xml\\" + xmlFilename + ".xml");

//xml(添加子节点、子节点的属性)

XmlDocument doc = new XmlDocument();

doc.Load(AppDomain.CurrentDomain.BaseDirectory + "Xml\\" + xmlFilename + ".xml");

XmlNode find = doc.SelectSingleNode("//media[@title=\"" + tmp.Text + "\"]");

if (find == null)

{

  XmlNode xmlroot = doc.SelectSingleNode("//media[@title=\"" + TreeView1.SelectedNode.Text + "\"]");

  XmlElement parentXmlNode = doc.CreateElement("media");

  xmlroot.AppendChild(parentXmlNode);

  parentXmlNode.SetAttribute("title", TextBox1.Text);

  parentXmlNode.SetAttribute("imagesUrl", "~/images/node.gif");

 doc.Save(AppDomain.CurrentDomain.BaseDirectory + "Xml\\" + xmlFilename + ".xml");

 }

//读节点属性

XmlNode aa= doc.SelectSingleNode("//"+addr+"[@code=\"" + code + "\"]");

private string getXmlAttribute(XmlNode aa)

    {       

        if (aa != null)

        {

            XmlElement aaNode = (XmlElement)aa;

            if (aaNode.HasAttribute("url"))

            {

               navtmp = "<a href=" + aaNode.Attributes["url"].Value + ">" + aaNode.Attributes["name"].Value + "</a>" + "--->" + navtmp;

   ;   getXmlAttribute(aaNode.ParentNode);

            }

        }

        return navtmp;

    }

//删除节点

XmlDocument doc = new XmlDocument();

doc.Load(AppDomain.CurrentDomain.BaseDirectory + "Xml\\" + xmlFilename + ".xml");

XmlNode xmlroot = doc.SelectSingleNode("//media[@title=\"" + selectText + "\"]");

xmlroot.ParentNode.RemoveChild(xmlroot);

doc.Save(AppDomain.CurrentDomain.BaseDirectory + "Xml\\" + xmlFilename + ".xml");

你可能感兴趣的:(xml)