LINQ to XML - 向 .csproj 文件中添加节点

3

我编写了一个代码生成器,可以生成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合并时会变得有些混乱。我该如何在新行中添加新节点?


看起来有点奇怪...正常的行为是在序列化时缩进和格式化XML。我不确定在xmlDoc.Save调用中明确设置SaveOptions为“None”是否会有所不同? - womp
@Womp - 没有什么区别,但还是谢谢你。 - Randy Minder
尝试使用 using (XmlWriter writer = XmlWriter.Create(projectFileName)) 创建一个 XmlWriter,然后使用 xmlDoc.Save(writer) - John Saunders
最终的好源代码是哪一个? - Kiquenet
1个回答

1
为什么你要使用StreamReader和XmlTextReader?只需将文件名传递给XDocument.Load即可。然后一切都会按照你的期望工作。
如果你自己创建阅读器,XDocument无法修改其设置,因此阅读器将报告空格,这些空格然后存储在XLinq树中,当写出时,它们会禁用编写器中的自动格式设置。因此,您可以在阅读器上将IgnoreWhitespaces设置为true,或者仅将输入作为文件名传递,这将使XDocument使用其自己的设置,其中包括IgnoreWhitespaces。
另外,请不要使用XmlTextReader,调用XmlReader.Create时会创建一个更符合规范的XML阅读器。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接