簡體   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