欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#操作XML通用方法汇总

程序员文章站 2022-03-26 08:43:50
 在.net的项目开发中,经常会对xml文件进行操作,由于xml文件可以实现跨平台传输,较多的应用在数据传输中,特总结以下几种常用的xml操作方法: 1.创建x...

 在.net的项目开发中,经常会对xml文件进行操作,由于xml文件可以实现跨平台传输,较多的应用在数据传输中,特总结以下几种常用的xml操作方法:

1.创建xml文档:

  /// <summary>
  /// 创建xml文档
  /// </summary>
  /// <param name="name">根节点名称</param>
  /// <param name="type">根节点的一个属性值</param>
  /// <returns>xmldocument对象</returns>  
  public static xmldocument createxmldocument(string name, string type)
  {
   xmldocument doc;
   try
   {
    doc = new xmldocument();
    doc.loadxml("<" + name + "/>");
    var rootele = doc.documentelement;
    rootele?.setattribute("type", type);
   }
   catch (exception er)
   {
    throw new exception(er.tostring());
   }
   return doc;
  }

2.读取xml文档中的数据:

  /// <summary>
  /// 读取数据
  /// </summary>
  /// <param name="path">路径</param>
  /// <param name="node">节点</param>
  /// <param name="attribute">属性名,非空时返回该属性值,否则返回串联值</param>
  /// <returns>string</returns>
  public static string read(string path, string node, string attribute)
  {
   var value = "";
   try
   {
    var doc = new xmldocument();
    doc.load(path);
    var xn = doc.selectsinglenode(node);
    if (xn != null && xn.attributes != null)
     value = (attribute.equals("") ? xn.innertext : xn.attributes[attribute].value);
   }
   catch (exception er)
   {
    throw new exception(er.tostring());
   }
   return value;
  }

3.对xml文档插入数据:

  /// <summary>
  /// 插入数据
  /// </summary>
  /// <param name="path">路径</param>
  /// <param name="node">节点</param>
  /// <param name="element">元素名,非空时插入新元素,否则在该元素中插入属性</param>
  /// <param name="attribute">属性名,非空时插入该元素属性值,否则插入元素值</param>
  /// <param name="value">值</param>
  /// <returns></returns>
  public static void insert(string path, string node, string element, string attribute, string value)
  {
   try
   {
    var doc = new xmldocument();
    doc.load(path);
    var xn = doc.selectsinglenode(node);
    if (element.equals(""))
    {
     if (!attribute.equals(""))
     {
      var xe = (xmlelement)xn;
      xe?.setattribute(attribute, value);
      //xe?.setattribute(attribute, value);
     }
    }
    else
    {
     var xe = doc.createelement(element);
     if (attribute.equals(""))
      xe.innertext = value;
     else
      xe.setattribute(attribute, value);
     xn?.appendchild(xe);
    }
    doc.save(path);
   }
   catch (exception er)
   {
    throw new exception(er.tostring());
   }
  }

4.修改xml文档中的数据:

  /// <summary>
  /// 修改数据
  /// </summary>
  /// <param name="path">路径</param>
  /// <param name="node">节点</param>
  /// <param name="attribute">属性名,非空时修改该节点属性值,否则修改节点值</param>
  /// <param name="value">值</param>
  /// <returns></returns>
  public static void update(string path, string node, string attribute, string value)
  {
   try
   {
    var doc = new xmldocument();
    doc.load(path);
    var xn = doc.selectsinglenode(node);
    var xe = (xmlelement)xn;
    if (attribute.equals(""))
    {
     if (xe != null) xe.innertext = value;
    }
    else
    {
     xe?.setattribute(attribute, value);
    }
    doc.save(path);
   }
   catch (exception er)
   {
    throw new exception(er.tostring());
   }
  }

5.删除xml文档中数据:

  /// <summary>
  /// 删除数据
  /// </summary>
  /// <param name="path">路径</param>
  /// <param name="node">节点</param>
  /// <param name="attribute">属性名,非空时删除该节点属性值,否则删除节点值</param>
  /// <returns></returns>
  public static void delete(string path, string node, string attribute)
  {
   try
   {
    var doc = new xmldocument();
    doc.load(path);
    var xn = doc.selectsinglenode(node);
    var xe = (xmlelement)xn;
    if (attribute.equals(""))
    {
     xn?.parentnode?.removechild(xn);
    }
    else
    {
     xe?.removeattribute(attribute);
    }
    doc.save(path);
   }
   catch (exception er)
   {
    throw new exception(er.tostring());
   }
  }

6.读取xml文档中指定节点数据:

  /// <summary>
  /// 获得xml文件中指定节点的节点数据
  /// </summary>
  /// <param name="path"></param>
  /// <param name="nodename"></param>
  /// <returns></returns>
  public static string getnodeinfobynodename(string path, string nodename)
  {
   var xmlstring = string.empty;
   try
   {
    var xml = new xmldocument();
    xml.load(path);
    var root = xml.documentelement;
    if (root == null) return xmlstring;
    var node = root.selectsinglenode("//" + nodename);
    if (node != null)
    {
     xmlstring = node.innertext;
    }
   }
   catch (exception er)
   {
    throw new exception(er.tostring());
   }
   return xmlstring;
  }

7.获取xml指定节点的属性:

  /// <summary> 
  /// 功能:读取指定节点的指定属性值  
  /// </summary>
  /// <param name="path"></param>
  /// <param name="strnode">节点名称</param> 
  /// <param name="strattribute">此节点的属性</param> 
  /// <returns></returns> 
  public string getxmlnodeattributevalue(string path, string strnode, string strattribute)
  {
   var strreturn = "";
   try
   {
    var xml = new xmldocument();
    xml.load(path);
    //根据指定路径获取节点 
    var xmlnode = xml.selectsinglenode(strnode);
    if (xmlnode != null)
    {
     //获取节点的属性,并循环取出需要的属性值 
     var xmlattr = xmlnode.attributes;
     if (xmlattr == null) return strreturn;
     for (var i = 0; i < xmlattr.count; i++)
     {
      if (xmlattr.item(i).name != strattribute) continue;
      strreturn = xmlattr.item(i).value;
      break;
     }
    }
   }
   catch (xmlexception xmle)
   {
    throw new exception(xmle.message);
   }
   return strreturn;
  }

8.设置xml文档中指定节点的属性:

 /// <summary> 
  /// 功能:设置节点的属性值  
  /// </summary>
  /// <param name="path"></param>
  /// <param name="xmlnodepath">节点名称</param> 
  /// <param name="xmlnodeattribute">属性名称</param> 
  /// <param name="xmlnodeattributevalue">属性值</param> 
  public void setxmlnodeattributevalue(string path, string xmlnodepath, string xmlnodeattribute, string xmlnodeattributevalue)
  {
   try
   {
    var xml = new xmldocument();
    xml.load(path);
    //可以批量为符合条件的节点的属性付值 
    var xmlnode = xml.selectnodes(xmlnodepath);
    if (xmlnode == null) return;
    foreach (var xmlattr in from xmlnode xn in xmlnode select xn.attributes)
    {
     if (xmlattr == null) return;
     for (var i = 0; i < xmlattr.count; i++)
     {
      if (xmlattr.item(i).name != xmlnodeattribute) continue;
      xmlattr.item(i).value = xmlnodeattributevalue;
      break;
     }
    }

   }
   catch (xmlexception xmle)
   {
    throw new exception(xmle.message);
   }
  }

9.读取xml文档指定节点的值:

  /// <summary>
  /// 读取xml资源中的指定节点内容
  /// </summary>
  /// <param name="source">xml资源</param>
  /// <param name="xmltype">xml资源类型:文件,字符串</param>
  /// <param name="nodename">节点名称</param>
  /// <returns>节点内容</returns>
  public static object getnodevalue(string source, xmltype xmltype, string nodename)
  {
   var xd = new xmldocument();
   if (xmltype == xmltype.file)
   {
    xd.load(source);
   }
   else
   {
    xd.loadxml(source);
   }
   var xe = xd.documentelement;
   xmlnode xn = null;
   if (xe != null)
   {
     xn= xe.selectsinglenode("//" + nodename);
    
   }
   return xn.innertext;
  }

10.更新xml文档指定节点的内容:

  /// <summary>
  /// 更新xml文件中的指定节点内容
  /// </summary>
  /// <param name="filepath">文件路径</param>
  /// <param name="nodename">节点名称</param>
  /// <param name="nodevalue">更新内容</param>
  /// <returns>更新是否成功</returns>
  public static bool updatenode(string filepath, string nodename, string nodevalue)
  {   
   try
   {
    bool flag;
    var xd = new xmldocument();
    xd.load(filepath);
    var xe = xd.documentelement;
    if (xe == null) return false;
    var xn = xe.selectsinglenode("//" + nodename);
    if (xn != null)
    {
     xn.innertext = nodevalue;
     flag = true;
    }
    else
    {
     flag = false;
    }
    return flag;
   }
   catch (exception ex)
   {
    throw new exception(ex.message);
   }
   
  }
复制代码
11.将对象转化为xml文件,并存入指定目录:

复制代码
  /// <summary>
  /// 将对象转化为xml,并写入指定路径的xml文件中
  /// </summary>
  /// <typeparam name="t">c#对象名</typeparam>
  /// <param name="item">对象实例</param>
  /// <param name="path">路径</param>
  /// <param name="jjdbh">标号</param>
  /// <param name="ends">结束符号(整个xml的路径类似如下:c:\xmltest\201111send.xml,其中path=c:\xmltest,jjdbh=201111,ends=send)</param>
  /// <returns></returns>
  public static string writexml<t>(t item, string path, string jjdbh, string ends)
  {
   if (string.isnullorempty(ends))
   {
    //默认为发送
    ends = "send";
   }
   //控制写入文件的次数
   var i = 0;
   //获取当前对象的类型,也可以使用反射typeof(对象名)
   var serializer = new xmlserializer(item.gettype());
   //xml的路径组合
   object[] obj = { path, "\\", jjdbh, ends, ".xml" };
   var xmlpath = string.concat(obj);
   while (true)
   {
    try
    {
     //用filestream方式创建文件不会出现“文件正在占用中,用file.create”则不行
     var fs = system.io.file.create(xmlpath);
     fs.close();
     textwriter writer = new streamwriter(xmlpath, false, encoding.utf8);
     var xml = new xmlserializernamespaces();
     xml.add(string.empty, string.empty);
     serializer.serialize(writer, item, xml);
     writer.flush();
     writer.close();
     break;
    }
    catch (exception)
    {
     if (i < 5)
     {
      i++;
      continue;
     }
     break;
    }
   }
   return serializetoxmlstr<t>(item, true);
  }

12.向一个已经存在的父节点中插入一个子节点:

  /// <summary> 
  /// 向一个已经存在的父节点中插入一个子节点 
  /// </summary>
  /// <param name="path"></param>
  /// <param name="parentnodepath">父节点</param>
  /// <param name="childnodename">子节点名称</param> 
  public void addchildnode(string path, string parentnodepath, string childnodename)
  {
   try
   {
    var xml = new xmldocument();
    xml.load(path);
    var parentxmlnode = xml.selectsinglenode(parentnodepath);
    xmlnode childxmlnode = xml.createelement(childnodename);
    if ((parentxmlnode) != null)
    {
     //如果此节点存在 
     parentxmlnode.appendchild(childxmlnode);
    }
    else
    {
     //如果不存在就放父节点添加 
     getxmlroot(path).appendchild(childxmlnode);
    }

   }
   catch (xmlexception xmle)
   {
    throw new exception(xmle.message);
   }
  }


以上的方法总结采用.net4.5版本和c#6.0语法,希望对大家的学习有所帮助,也希望大家多多支持。