如何用C#对Xml怎么在手机上对文件进行修改的修改

天极传媒:天极网全国分站
您现在的位置: >>
用C#把文件转换为XML
using Susing System.Dusing System.Cusing System.ComponentMusing System.Windows.Fusing System.IO;using System.X
namespace MyWindows{ /// &summary& /// 这个示例演示如何把Office文件编码为xml文件以及如何把生成的xml文件转换成Office文件 /// 把文件转换成xml格式,然后就可以用web服务,.NET Remoting,WinSock等传送了(其中后两者可以不转换也可以传送) /// xml解决了在多层架构中数据传输的问题,比如说在客户端可以用Web服务获取服务器端的office文件,修改后再回传给服务器 /// 只要把文件转换成xml格式,便有好多方案可以使用了,而xml具有平台无关性,你可以在服务端用.net用发布web服务,然后客户端用 /// Java写一段applit小程序来处理发送过来的文件,当然我举的例子几乎没有任何显示意义,它却给了我们不少的启示. /// 另外如果你的解决方案是基于多平台的,那么他们之间的交互最好不要用远程应用程序接口调用(RPC),应该尽量用基于文档的交互, /// 比如说.net下的MSMQ,j2ee的JMQ. ///  /// 示例中设计到好多的类,我并没有在所有的地方做过多注释,有不明白的地方请参阅MSDN,这是偶第一个windows程序,有不对的地方 /// 欢迎各位指导  /// &/summary& public class Form1 : System.Windows.Forms.Form {
  /// &summary&  /// 声明四个Button,一个OpenFileDialog,一个SaveFileDialog,以及两个XmlDocument  /// &/summary&  private System.Windows.Forms.Button button1;  private System.Windows.Forms.Button button2;  private System.Windows.Forms.OpenFileDialog openFileDialog1;  private System.Windows.Forms.SaveFileDialog saveFileDialog1;  private System.Windows.Forms.Button button3;  private System.Windows.Forms.Button button4;  private System.Xml.XmlDocument mXmlD  private System.Xml.XmlD  private System.ComponentModel.Container components =
  public Form1()  {   //   // Windows 窗体设计器支持所必需的   //   InitializeComponent();
   //   // TODO: 在 InitializeComponent 调用后添加任何构造函数代码   //  }
  /// &summary&  /// 清理所有正在使用的资源。  /// &/summary&  protected override void Dispose( bool disposing )  {   if( disposing )   {    if(components != null)    {     components.Dispose();    }   }   base.Dispose( disposing );  }
  #region Windows 窗体设计器生成的代码  /// &summary&  /// 设计器支持所需的方法 - 不要使用代码编辑器修改  /// 此方法的内容。  /// &/summary&  private void InitializeComponent()  {   this.button1 = new System.Windows.Forms.Button();   this.button2 = new System.Windows.Forms.Button();   this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();   this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();   this.button3 = new System.Windows.Forms.Button();   this.button4 = new System.Windows.Forms.Button();   this.SuspendLayout();   //    // button1   //    this.button1.Location = new System.Drawing.Point(96, 32);   this.button1.Name = "button1";   this.button1.TabIndex = 0;   this.button1.Text = "生成xml";   this.button1.Click += new System.EventHandler(this.button1_Click);   //    // button2   //    this.button2.Location = new System.Drawing.Point(96, 80);   this.button2.Name = "button2";   this.button2.TabIndex = 1;   this.button2.Text = "生成doc";   this.button2.Click += new System.EventHandler(this.button2_Click);   //    // button3   //    this.button3.Location = new System.Drawing.Point(8, 32);   this.button3.Name = "button3";   this.button3.TabIndex = 2;   this.button3.Text = "加载doc";   this.button3.Click += new System.EventHandler(this.button3_Click);   //    // button4   //    this.button4.Location = new System.Drawing.Point(8, 80);   this.button4.Name = "button4";   this.button4.TabIndex = 3;   this.button4.Text = "加载xml";   this.button4.Click += new System.EventHandler(this.button4_Click);   //    // Form1   //    this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);   this.ClientSize = new System.Drawing.Size(184, 141);   this.Controls.Add(this.button4);   this.Controls.Add(this.button3);   this.Controls.Add(this.button2);   this.Controls.Add(this.button1);   this.Name = "Form1";   this.Text = "Form1";   this.ResumeLayout(false);   //   //手工注册一下Load和Closed事件   //   this.Load += new System.EventHandler(this.Form1_Load);   this.Closed += new System.EventHandler(this.Form1_Closed);
  }  #endregion
  /// &summary&  /// 从这个入口启动窗体   /// &/summary&  static void Main()  {   Application.Run(new Form1());  }  /// &summary&  /// 把加载的Office文件转换为xml文件  /// &/summary&  /// &param name="sender"&&/param&  /// &param name="e"&&/param&  private void button1_Click(object sender, System.EventArgs e)  {    saveFileDialog1.Filter = "xml 文件|*.xml";//设置打开对话框的文件过滤条件   saveFileDialog1.Title = "保存成 xml 文件";//设置打开对话框的标题   saveFileDialog1.FileName="";   saveFileDialog1.ShowDialog();//打开对话框
   if(saveFileDialog1.FileName != "")//检测用户是否输入了保存文件名   {    mXmlDoc.Save(saveFileDialog1.FileName);//用私有对象mXmlDoc保存文件,mXmlDoc在前面声明过    MessageBox.Show("保存成功");   }   }
  /// &summary&  /// 把加载的xml文件转换为Office文件  /// &/summary&  /// &param name="sender"&&/param&  /// &param name="e"&&/param&  private void button2_Click(object sender, System.EventArgs e)  {   //从私有对象dox里选取me节点,这里的一些对xml对象的操作详细说明可以参考msdn以获取更多信息   XmlNode node=doc.DocumentElement .SelectSingleNode("me") ;   XmlElement ele=(XmlElement)//获取一个xml元素   string pic=ele.GetAttribute ("aa");//获取ele元素的aa属性并报讯在一个临时字符串变量pic
   byte[] bytes=Convert.FromBase64String (pic);//声明一个byte[]用来存放Base64解码转换过来的数据流     //从保存对话框里获取文件保存地址   saveFileDialog1.Filter = "Office Documents(*.doc, *.xls, *.ppt)|*.*.*.ppt";   saveFileDialog1.Title = "保存成 office 文件";   saveFileDialog1.FileName="";   saveFileDialog1.ShowDialog();
   if(saveFileDialog1.FileName != "")   {    //创建文件流并保存    FileStream outfile=new System.IO .FileStream (saveFileDialog1.FileName,System.IO.FileMode.CreateNew);    outfile.Write(bytes,0,(int)bytes.Length );    MessageBox.Show("保存成功");   }
  /// &summary&  /// 加载窗口时的一些初始化行为  /// &/summary&  /// &param name="sender"&&/param&  /// &param name="e"&&/param&  public void Form1_Load(object sender, System.EventArgs e)  {   MessageBox.Show("欢迎使用蛙蛙牌文档转换器");  }  /// &summary&  /// 卸载窗体时把临时变量全部释放  /// &/summary&  /// &param name="sender"&&/param&  /// &param name="e"&&/param&  public void Form1_Closed(object sender, System.EventArgs e)  {   mXmlDoc=   doc=  }  /// &summary&  /// 加载office文件并编码序列花为一个XmlDocument变量  /// &/summary&  /// &param name="sender"&&/param&  /// &param name="e"&&/param&  private void button3_Click(object sender, System.EventArgs e)  {   string strFileN   openFileDialog1.Filter = "Office Documents(*.doc, *.xls, *.ppt)|*.*.*.ppt" ;   openFileDialog1.FilterIndex = 1;   openFileDialog1.FileName = "";   openFileDialog1.ShowDialog();   strFileName = openFileDialog1.FileN   if(strFileName.Length != 0)   {    System.IO.FileStream inFile=new FileStream(strFileName,System.IO.FileMode.Open,System.IO.FileAccess.Read);    byte[] binaryData=new byte [inFile.Length];    inFile.Read(binaryData, 0,(int)inFile.Length);    string mStr=Convert.ToBase64String(binaryData);    string hh=mS    mXmlDoc=new System.Xml.XmlDocument();      mStr=string.Format ("&wawa&&me aa=\"{0}\"/&&/wawa&",mStr);    mXmlDoc.LoadXml( mStr);    MessageBox.Show("加载成功");   }
  }  /// &summary&  /// 加载xml文件到私有对象dox  /// &/summary&  /// &param name="sender"&&/param&  /// &param name="e"&&/param&  private void button4_Click(object sender, System.EventArgs e)  {   string strFileN   openFileDialog1.Filter = "xml 文件|*.xml" ;   openFileDialog1.FilterIndex = 1;   openFileDialog1.FileName = "";   openFileDialog1.ShowDialog();   strFileName = openFileDialog1.FileN   //If the user does not cancel, open the document.   if(strFileName.Length != 0)   {    doc=new XmlDocument();    doc.Load(strFileName);    MessageBox.Show("加载成功");   }
(作者:蛙娃王子责任编辑:方舟)
天极新媒体&最酷科技资讯扫码赢大奖
* 网友发言均非本站立场,本站不在评论栏推荐任何网店、经销商,谨防上当受骗!
笔记本手机数码家电怎样在C#里对xml文件进行修改,新增,删除,插入操作?
已知有一个XML文件(bookstore.xml)如下:&?xml version="1.0" encoding="gb2312"?&&bookstore&&book genre="fantasy" ISBN="2-3631-4"&&title&Oberon's Legacy&/title&&author&Corets, Eva&/author&&price&5.95&/price&&/book&&/bookstore&
1、往&bookstore&节点中插入一个&book&节点:
XmlDocument xmlDoc=new XmlDocument();xmlDoc.Load("bookstore.xml");XmlNode root=xmlDoc.SelectSingleNode("bookstore");//查找&bookstore&XmlElement xe1=xmlDoc.CreateElement("book");//创建一个&book&节点xe1.SetAttribute("genre","李赞红");//设置该节点genre属性xe1.SetAttribute("ISBN","2-3631-4");//设置该节点ISBN属性
XmlElement xesub1=xmlDoc.CreateElement("title");xesub1.InnerText="CS从入门到精通";//设置文本节点xe1.AppendChild(xesub1);//添加到&book&节点中XmlElement xesub2=xmlDoc.CreateElement("author");xesub2.InnerText="候捷";xe1.AppendChild(xesub2);XmlElement xesub3=xmlDoc.CreateElement("price");xesub3.InnerText="58.3";xe1.AppendChild(xesub3);
root.AppendChild(xe1);//添加到&bookstore&节点中xmlDoc.Save("bookstore.xml");
//================结果为:
&?xml version="1.0" encoding="gb2312"?&&bookstore&&book genre="fantasy" ISBN="2-3631-4"&&title&Oberon's Legacy&/title&&author&Corets, Eva&/author&&price&5.95&/price&&/book&&book genre="李赞红" ISBN="2-3631-4"&&title&CS从入门到精通&/title&&author&候捷&/author&&price&58.3&/price&&/book&&/bookstore&
2、修改节点:将genre属性值为“李赞红“的节点的genre值改为“update李赞红”,将该节点的子节点&author&的文本修改为“亚胜”。
XmlNodeList nodeList=xmlDoc.SelectSingleNode("bookstore").ChildN//获取bookstore节点的所有子节点foreach(XmlNode xn in nodeList)//遍历所有子节点{XmlElement xe=(XmlElement)//将子节点类型转换为XmlElement类型if(xe.GetAttribute("genre")=="李赞红")//如果genre属性值为“李赞红”{xe.SetAttribute("genre","update李赞红");//则修改该属性为“update李赞红”
XmlNodeList nls=xe.ChildN//继续获取xe子节点的所有子节点
foreach(XmlNode xn1 in nls)//遍历{XmlElement xe2=(XmlElement)xn1;//转换类型if(xe2.Name=="author")//如果找到{xe2.InnerText="亚胜";//则修改//找到退出来就可以了}}}}
xmlDoc.Save("bookstore.xml");//保存。
//=================
最后结果为:
&?xml version="1.0" encoding="gb2312"?&&bookstore&&book genre="fantasy" ISBN="2-3631-4"&&title&Oberon's Legacy&/title&&author&Corets, Eva&/author&&price&5.95&/price&&/book&&book genre="update李赞红" ISBN="2-3631-4"&&title&CS从入门到精通&/title&&author&亚胜&/author&&price&58.3&/price&&/book&&/bookstore&
3、删除 &book genre="fantasy" ISBN="2-3631-4"&节点的genre属性,删除 &book genre="update李赞红" ISBN="2-3631-4"&节点。
XmlNodeList xnl=xmlDoc.SelectSingleNode("bookstore").ChildN
foreach(XmlNode xn in xnl){XmlElement xe=(XmlElement)
if(xe.GetAttribute("genre")=="fantasy"){xe.RemoveAttribute("genre");//删除genre属性}else if(xe.GetAttribute("genre")=="update李赞红"){xe.RemoveAll();//删除该节点的全部内容}}xmlDoc.Save("bookstore.xml");
//====================
最后结果为:
&?xml version="1.0" encoding="gb2312"?&&bookstore&&book ISBN="2-3631-4"&&title&Oberon's Legacy&/title&&author&Corets, Eva&/author&&price&5.95&/price&&/book&&book&&/book&&/bookstore&
4、显示所有数据。
XmlNode xn=xmlDoc.SelectSingleNode("bookstore");
XmlNodeList xnl=xn.ChildN
foreach(XmlNode xnf in xnl){XmlElement xe=(XmlElement)Console.WriteLine(xe.GetAttribute("genre"));//显示属性值Console.WriteLine(xe.GetAttribute("ISBN"));
XmlNodeList xnf1=xe.ChildNforeach(XmlNode xn2 in xnf1){Console.WriteLine(xn2.InnerText);//显示子节点点文本}} 另有:using Susing System.IO;using System.Wusing System.Tusing System.Xusing System.C
namespace ShopWeb.Class{ /// &summary& /// Log 的摘要说明。 /// &/summary& public class Log {
private XmlDocument xmlLog=new XmlDocument();
private HttpContext context=HttpContext.C
private string
xmlPath="";
/// &summary&
/// 构造函数
/// &/summary&
/// &param name="XmlPath"&&/param&
public Log(string XmlPath)
xmlPath=XmlP
xmlLog.Load(context.Server.MapPath(XmlPath));
/// &summary&
/// 增加一个节点,该节点由子节点构成
/// &/summary&
/// &param name="HTChilds"&&/param&
/// &param name="ParentName"&&/param&
/// &returns&&/returns&
public bool AddNodeByChild(Hashtable HTChilds ,string ParentName)
XmlNode Parent=xmlLog.CreateElement(ParentName);
IDictionaryEnumerator myEnumerator=HTChilds.GetEnumerator();
while(myEnumerator.MoveNext())
Child=xmlLog.CreateElement(myEnumerator.Key.ToString());
Child.InnerText=myEnumerator.Value.ToString();
Parent.AppendChild(Child);
xmlLog.DocumentElement.AppendChild(Parent);
xmlLog.Save(context.Server.MapPath(xmlPath));
/// &summary&
增加一个节点 该节点由属性构成
/// &/summary&
/// &param name="htAttributes"&&/param&
/// &param name="NodeName"&&/param&
/// &returns&&/returns&
public bool AddNodeByAttribute(Hashtable htAttributes,string NodeName)
XmlNode AddNode=xmlLog.CreateElement(NodeName);
IDictionaryEnumerator myEnumerator=htAttributes.GetEnumerator();
while(myEnumerator.MoveNext())
atr=xmlLog.CreateAttribute(myEnumerator.Key.ToString());
atr.InnerText=myEnumerator.Value.ToString();
AddNode.Attributes.Append(atr);
xmlLog.DocumentElement.AppendChild(AddNode);
xmlLog.Save(context.Server.MapPath(xmlPath));
/// &summary&
/// 或得指定查询节点得子节点数目
/// &/summary&
/// &param name="QueryPath"&&/param&
/// &returns&&/returns&
public int ChildCount(string QueryPath)
XmlNode ResultNodes=xmlLog.SelectSingleNode(QueryPath);
return ResultNodes.ChildNodes.C
return -1;
/// &summary&
删除指定路径的节点
/// &/summary&
/// &param name="QueryPath"&&/param&
/// &returns&&/returns&
public bool DelelteNode(string QueryPath)
XmlNodeList ResultNodes=xmlLog.SelectNodes(QueryPath);
for(int i=0;i&ResultNodes.Ci++)
XmlNode ParentNode=ResultNodes[i].ParentN
ParentNode.RemoveChild(ResultNodes[i]);
xmlLog.Save(context.Server.MapPath(xmlPath));
/// &summary&
/// 查询节点
/// &/summary&
/// &param name="QueryPath"&&/param&
/// &returns&&/returns&
public XmlNodeList QueryNode(string QueryPath)
XmlNodeList ResultNodes=xmlLog.SelectNodes(QueryPath);
return ResultN
没有更多推荐了,
加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!& & 在.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)
doc = new XmlDocument();
doc.LoadXml("&" + name + "/&");
var rootEle = doc.DocumentE
rootEle?.SetAttribute("type", type);
catch (Exception er)
throw new Exception(er.ToString());
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 = "";
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());
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)
var doc = new XmlDocument();
doc.Load(path);
var xn = doc.SelectSingleNode(node);
if (element.Equals(""))
if (!attribute.Equals(""))
var xe = (XmlElement)
xe?.SetAttribute(attribute, value);
//xe?.SetAttribute(attribute, value);
var xe = doc.CreateElement(element);
if (attribute.Equals(""))
xe.InnerText =
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)
var doc = new XmlDocument();
doc.Load(path);
var xn = doc.SelectSingleNode(node);
var xe = (XmlElement)
if (attribute.Equals(""))
if (xe != null) xe.InnerText =
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)
var doc = new XmlDocument();
doc.Load(path);
var xn = doc.SelectSingleNode(node);
var xe = (XmlElement)
if (attribute.Equals(""))
xn?.ParentNode?.RemoveChild(xn);
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.E
var xml = new XmlDocument();
xml.Load(path);
var root = xml.DocumentE
if (root == null) return xmlS
var node = root.SelectSingleNode("//" + nodeName);
if (node != null)
xmlString = node.InnerT
catch (Exception er)
throw new Exception(er.ToString());
return xmlS
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 = "";
var xml = new XmlDocument();
xml.Load(path);
//根据指定路径获取节点
var xmlNode = xml.SelectSingleNode(strNode);
if (xmlNode != null)
//获取节点的属性,并循环取出需要的属性值
var xmlAttr = xmlNode.A
if (xmlAttr == null) return strR
for (var i = 0; i & xmlAttr.C i++)
if (xmlAttr.Item(i).Name != strAttribute) continue;
strReturn = xmlAttr.Item(i).V
catch (XmlException xmle)
throw new Exception(xmle.Message);
return strR
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)
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.C i++)
if (xmlAttr.Item(i).Name != xmlNodeAttribute) continue;
xmlAttr.Item(i).Value = xmlNodeAttributeV
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);
xd.LoadXml(source);
var xe = xd.DocumentE
XmlNode xn = null;
if (xe != null)
xn= xe.SelectSingleNode("//" + nodeName);
return xn.InnerT
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)
var xd = new XmlDocument();
xd.Load(filePath);
var xe = xd.DocumentE
if (xe == null) return false;
var xn = xe.SelectSingleNode("//" + nodeName);
if (xn != null)
xn.InnerText = nodeV
flag = true;
flag = false;
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)
//用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();
catch (Exception)
if (i & 5)
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)
var xml = new XmlDocument();
xml.Load(path);
var parentXmlNode = xml.SelectSingleNode(parentNodePath);
XmlNode childXmlNode = xml.CreateElement(childnodename);
if ((parentXmlNode) != null)
//如果此节点存在
parentXmlNode.AppendChild(childXmlNode);
//如果不存在就放父节点添加
GetXmlRoot(path).AppendChild(childXmlNode);
catch (XmlException xmle)
throw new Exception(xmle.Message);
& &以上的方法总结采用.net4.5版本和c#6.0语法
阅读(...) 评论()

我要回帖

更多关于 怎么在手机上对文件进行修改 的文章

 

随机推荐