备份C#写入csproj的代码
2015-05-22 16:10:52 访问(2138) 赞(0) 踩(0)
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = null;
try
{
string fileName = @"C:\Projectes\eKing\2015\WindowsSeriveStudy\HW\HEW\HEW.csproj";
FileInfo fi = new FileInfo(fileName);
xmlDoc = new XmlDocument();
xmlDoc.Load(fileName);
// MessageBox.Show(xmlDoc.InnerXml);
XmlNode xnProject = XmlNodeFind(xmlDoc.ChildNodes, "Project");
if (xnProject == null)
{
MessageBox.Show("没有找到Project节点。");
return;
}
XmlNode nResult = null;
int findIndex = 0;
foreach (XmlNode xn in xnProject.ChildNodes)
{
if (xn == null)
continue;
if (xn.Name == "ItemGroup")
{
++findIndex;
nResult = xn;
if (findIndex == 2)
{
break;
}
}
}
if (nResult == null)
{
MessageBox.Show("没有找到ItemGroup节点。");
return;
}
string newClassName = "Class" + DateTime.Now.ToString("HHmmss");
string classValue =BlankClass(newClassName);
string classNameFullName = fi.Directory.FullName + "\\" + newClassName + ".cs";
File.WriteAllText(classNameFullName, classValue, System.Text.Encoding.Unicode);
string xmlUrl = "";
// 命名空间使用方法:
// XmlNamespaceManager nsmgr = new XmlNamespaceManager(new XmlDocument().NameTable); //声明一个命名空间管理器
//nsmgr.AddNamespace("ns", xmlUrl);//向管理器添加一个命名空间连接,其中ns为添加命名空间的名称,xmlUrl为命名空间的链接。两个参数都是string类型。
//jobNode.SelectSingleNode("ns:trigger/ns:cron", nsmgr)//使用命名空间查找节点。注意其中的ns和nsmgr
//其实对于你的问题只需要在创建要加入的节点时指明一个xmlUrl就可以啦:
//XmlElement jobElement = xmlDoc.CreateElement("job", xmlUrl);
//如果添加的命名空间和所在命名控件一致时,xmlns属性会自动隐藏
//创建一个<book>节点
// XmlElement xe1 = xmlDoc.CreateElement("Compile", "url", xmlDoc.DocumentElement.NamespaceURI);
// 同父节点的xmlns //
string namespaceUrl = "http://schemas.microsoft.com/developer/msbuild/2003";
XmlElement xe1 = xmlDoc.CreateElement("Compile", namespaceUrl);
//设置该节点genre属性
xe1.SetAttribute("Include", newClassName + ".cs");
nResult.AppendChild(xe1);
XmlAttribute xa = xe1.Attributes["xmlns"];
if(xa!=null)
xe1.Attributes.Remove(xa);
xmlDoc.Save(fi.FullName);
MessageBox.Show("OK");
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
finally
{
if (xmlDoc != null)
xmlDoc = null;
}
}
/// <summary>
///
/// </summary>
/// <param name="newClassName"></param>
/// <returns></returns>
public string BlankClass(string newClassName)
{
return @"
using System;
using System.Collections.Generic;
using System.Text;
namespace HEW
{
public class " + newClassName + @"
{
public " + newClassName + @"()
{
}
public string c = """";
}
}
";
}
/// <summary>
/// 通过XML的名称找到XML的节点
/// </summary>
/// <param name="xnl"></param>
/// <param name="theName"></param>
/// <returns></returns>
public XmlNode XmlNodeFind(XmlNodeList xnl,string theName)
{
XmlNode theResult = null;
foreach (XmlNode xn in xnl)
{
if (xn.Name == theName)
return xn;
theResult = XmlNodeFind(xn.ChildNodes, theName);
if (theResult != null)
return theResult;
}
return null;
}
}
标签:
备份C#写入csproj的代码 


上一条:
下一条:
相关评论
发表评论