简体   繁体   中英

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

I've written a code generator, that generates C# files. If the file being generated is new, I need to add a reference to it to our .csproj file. I have the following method that adds a 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 fine. However, it doesn't add the node on a new line. It will append it to the previous line in the .csproj file. This makes for a bit of a mess when doing TFS merging. How can I add the new node on a new line?

Why are you using StreamReader and then XmlTextReader? Just pass the filename to the XDocument.Load. Then everything works as you would expect. If you create the reader on your own XDocument can't modify its settings and thus the reader will report whitespaces which are then stored in the XLinq tree and when written out they disable automatic formatting in the writer. So you can either set IgnoreWhitespaces to true on your reader, or pass the input just as a filename, which will let XDocument use its own settings which will include IgnoreWhitespaces.

As a side note, please don't use XmlTextReader, a more spec compliant XML reader is created when you call XmlReader.Create.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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