繁体   English   中英

LINQ to XML - 将节点添加到.csproj文件

[英]LINQ to XML - Adding a node to a .csproj file

我编写了一个生成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合并时会造成一些混乱。 如何在新行上添加新节点?

你为什么使用StreamReader然后使用XmlTextReader? 只需将文件名传递给XDocument.Load即可。 然后一切都按照您的预期运作。 如果您自己创建阅读器XDocument无法修改其设置,因此阅读器将报告随后存储在XLinq树中的空格,并在写出时禁用编写器中的自动格式。 因此,您可以在阅读器上将IgnoreWhitespaces设置为true,或者将输入作为文件名传递,这将使XDocument使用自己的设置,其中包括IgnoreWhitespaces。

作为旁注,请不要使用XmlTextReader,当您调用XmlReader.Create时,会创建一个更符合规范的XML阅读器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM