asp.net C#对xml文档创建 修改 删除 查找

作者:袖梨 2022-06-25

1、创建 XML

导入命名空间:

 代码如下 复制代码

using System.Xml;

//创建 XML 对象

XmlDocument  xmlDocument = new XmlDocument();

// 声明 XML

 XmlDeclaration xmlDeclare =xmlDocument.CreateXmlDeclaration("1.0","utf-8",null);

//创建根节点

XmlElement elementRoot =xmlDocument.CreateElement("Nodes");

xmlDocument.AppendChild(elementRoot);  

//创建节点 Day

XmlElement elementDay = xmlDocument.CreateElement("Day");

       //给节点Day设置属性,并赋值

elementDay.SetAttribute("date","今天"); 

elementRoot.AppendChild(elementDay);


//创建 Day 的子节点Part

XmlElement elementPart = xmlDocument.CreateElement("Part");

elementPart.InnerText = " aaa";

 elementDay.AppendChild(elementPart);

//保存到 XML 文件件下

xmlDocument.Save("./myXml.xml");

 

xml 生成数据:

    

              aaa

    


2.读写XML文件

 

 代码如下 复制代码



 
  加菲尔德
  5555555
  纽约
  26/10/1978
 

 
  迈克
  6666666
  纽约
  12/02/1978
 

*********************************************************************

·使用Document读取及写入XML方法

  private void xmlfun()
  {
   XmlDocument doc = new XmlDocument();
   doc.Load(Server.MapPath("phone.xml"));

   XmlElement node = doc.CreateElement("phone");
   XmlAttribute atr = doc.CreateAttribute("id");
   atr.InnerText = "003";
   node.Attributes.Append(atr);

   XmlNode xnode = (XmlNode)doc.CreateElement("Name");
   xnode.InnerText="testName";
   node.AppendChild(xnode);

   xnode = (XmlNode)doc.CreateElement("Number");
   xnode.InnerText="119";
   node.AppendChild(xnode);
   xnode = (XmlNode)doc.CreateElement("City");
   xnode.InnerText="cs";
   node.AppendChild(xnode);
   xnode = (XmlNode)doc.CreateElement("DateOfBirth");
   xnode.InnerText="12/02/1978";
   node.AppendChild(xnode);
   doc.DocumentElement.InsertAfter(node,doc.DocumentElement.LastChild);

   doc.Save(Server.MapPath("phone1.xml"));   //必须要存为不同的文件

  }

 

·使用XmlTextWriter写入XML方法

 代码如下 复制代码

  private void xmlwriter()
  {
   XmlTextWriter writer= new XmlTextWriter(Server.MapPath("phone4.xml"),null);
   writer.Formatting = Formatting.Indented;  //缩进格式
   writer.Indentation =4;

   writer.WriteStartDocument();

   writer.WriteStartElement("Person");

   writer.WriteStartAttribute("ID",null);
   writer.WriteString("004");
   writer.WriteEndAttribute();

   writer.WriteStartElement("Name");
   writer.WriteString("testWriterName");
   writer.WriteEndElement();

   writer.WriteStartElement("Number");
   writer.WriteString("88888");
   writer.WriteEndElement();

   writer.WriteStartElement("City");
   writer.WriteString("testWriterCity");
   writer.WriteEndElement();

   writer.Flush();
   writer.Close();

  }

 

·使用XmlTextReader读取XML方法

 代码如下 复制代码

  private void xmlread()
  {
      XmlTextReader reader = new XmlTextReader(Server.MapPath("phone.xml"));
      while(reader.Read())
      {
          if(reader.LocalName.Equals("Name") || reader.LocalName.Equals("Number"))
      {
      this.Label1.Text += reader.ReadString()+"t";
  }


 

·作用SqlCommand.ExecuteXmlReader()取得XML

 代码如下 复制代码

SqlConnecting conn = new SqlConnection(CONNSTR);
SqlCommand cmd = new SqlCommand("select fname from employee for xml auto",conn);
conn.open();
XmlReader reader = cmd.ExecuteXmlReader();
......
################ 所取xml数据格式 #################


......


3.查找xml


      Front line
      sole
      #roadStyle
     
       
               114.0456,22.324
           

     

   

如何根据Name的值找到这个Placemark
让后插入数据到
coordinates节点中呢。

 代码如下 复制代码
XmlElement Chid_Elent = Doc.DocumentElement; //得到XML的根节点
 if (Chid_Elent.ChildNodes.Count > 0)//如果根节点下有子节点
  {
       foreach (XmlElement Elent in Chid_Elent.ChildNodes)//循环获取节点值
       {
             value=Elent.InnerText;//得到值
             Elent.InnerText=vaue; //或者赋值  value为外部变量
       }
}

最后save(路径)


4、显示所有数据

 

 代码如下 复制代码

 

XmlNode xn=xmlDoc.SelectSingleNode("bookstore");
XmlNodeList xnl=xn.ChildNodes;

foreach(XmlNode xnf in xnl)
{
XmlElement xe=(XmlElement)xnf;
Console.WriteLine(xe.GetAttribute("genre"));//显示属性值
Console.WriteLine(xe.GetAttribute("ISBN"));

XmlNodeList xnf1=xe.ChildNodes;
foreach(XmlNode xn2 in xnf1)
{
Console.WriteLine(xn2.InnerText);//显示子节点点文本
}
}

最后附一个C#操作Xml通用工具类

 代码如下 复制代码

using System;
using System.Xml;

namespace WLerp.Common.Util
{
    ///


    /// Xml 操作工具类
    ///

    public sealed class XmlUtil
    {
        private XmlUtil() { }

        ///


        /// 创建节点
        ///

        ///
        ///
        ///
        public static XmlNode AppendElement(XmlNode node, string newElementName)
        {
            return AppendElement(node, newElementName, null);
        }

        ///


        /// 创建节点
        ///

        ///
        ///
        ///
        ///
        public static XmlNode AppendElement(XmlNode node, string newElementName, string innerValue)
        {
            XmlNode oNode;
            if (node is XmlDocument)
            {
                oNode = node.AppendChild(((XmlDocument)node).CreateElement(newElementName));
            }
            else
            {
                oNode = node.AppendChild(node.OwnerDocument.CreateElement(newElementName));
            }

            if (innerValue != null)
            {
                oNode.AppendChild(node.OwnerDocument.CreateTextNode(innerValue));
            }
            return oNode;
        }

        ///


        /// 创建属性
        ///

        ///
        ///
        ///
        ///
        public static XmlAttribute CreateAttribute(XmlDocument xmlDocument, string name, string value)
        {
            XmlAttribute oAtt = xmlDocument.CreateAttribute(name);
            oAtt.Value = value;
            return oAtt;
        }

        ///


        /// 设置属性的值
        ///

        ///
        ///
        ///
        public static void SetAttribute(XmlNode node, string attributeName, string attributeValue)
        {
            if (node.Attributes[attributeName] != null)
            {
                node.Attributes[attributeName].Value = attributeValue;
            }
            else
            {
                node.Attributes.Append(CreateAttribute(node.OwnerDocument, attributeName, attributeValue));
            }
        }

        ///


        /// 获取属性的值
        ///

        ///
        ///
        ///
        ///
        public static string GetAttribute(XmlNode node, string attributeName, string defaultValue)
        {
            XmlAttribute att = node.Attributes[attributeName];
            if (att != null)
            {
                return att.Value;
            }
            else
            {
                return defaultValue;
            }
        }

        ///


        /// 获取节点的值
        ///

        ///
        ///
        ///
        ///
        public static string GetNodeValue(XmlNode parentNode, string nodeXPath, string defaultValue)
        {
            XmlNode node = parentNode.SelectSingleNode(nodeXPath);
            if (node.FirstChild != null)
            {
                return node.FirstChild.Value;
            }
            else if (node != null)
            {
                return node.Value;
            }
            else
            {
                return defaultValue;
            }
        }
    }
}

相关文章

精彩推荐