LINQ to XML - Adding a node file to a .csproj file

I wrote a code generator that generates C # files. If the file you are creating is new, I need to add a link to it in our .csproj file. I have the following method that adds node to a .csproj file.

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);
}

This method works just fine. However, it does not add node to the new line. It will add it to the previous line in the .csproj file. This leads to some confusion when merging TFS. How to add a new node to a new line?

+3
source share
1 answer

StreamReader, XmlTextReader? XDocument.Load. , . XDocument, , , , , XLinq, , . , IgnoreWhitespaces true , , , XDocument , IgnoreWhitespaces.

, , XmlTextReader, XmlReader.Create XML-, .

+1
source

Source: https://habr.com/ru/post/1750741/


All Articles