我编写了一个代码生成器,可以生成C#文件。如果正在生成的文件是新文件,则需要将其引用添加到我们的.csproj文件中。我有以下方法可以向.csproj文件添加节点。
private static void AddToProjectFile(string projectFileName, string projectFileEntry)
{
StreamReader streamReader = new StreamReader(projectFileName);
XmlTextReader xmlReader = new XmlTextReader(streamReader);
XElement element;
XNamespace nameSpace;
// Load the xml document
XDocument xmlDoc = XDocument.Load(xmlReader);
// Get the xml namespace
nameSpace = xmlDoc.Root.Name.Namespace;
// Close the reader so we can save the file back.
streamReader.Close();
// Create the new element we want to add.
element = new XElement(nameSpace + "Compile", new XAttribute("Include", projectFileEntry));
// Add the new element.
xmlDoc.Root.Elements(nameSpace + "ItemGroup").ElementAt(1).Add(element);
xmlDoc.Save(projectFileName);
}
这种方法很好用。但是,它不会将节点添加到新行中,而是将其附加到.csproj文件中的上一行。这样在进行TFS合并时会变得有些混乱。我该如何在新行中添加新节点?
using (XmlWriter writer = XmlWriter.Create(projectFileName))
创建一个XmlWriter
,然后使用xmlDoc.Save(writer)
。 - John Saunders