Christopher B. Adkins
Christopher B. Adkins

Reputation: 3577

XML creation with c#

First off here is my code.

IEnumerable<XElement> targetDirectory =
    from XElement e in workingXmlDocument.Descendants(wixNS + "Directory")
    where e.Attribute("Id").Value == "TARGETDIR"
    select e;
foreach (var now in targetDirectory)
{
    now.Add(XElement.Parse("<Directory Id='" + fileVariable.Directory.Name 
                                             + @"' />"));
}

Here is what I am trying to do. I am trying to search for every Directory element with the attribute Id valued at TARGETDIR. Then I place a new directory element inside that one with a name of a file's directory. It does just that. The problem is that it just puts all the directories into a single line (no line breaks, no indent, nothing, just the raw data), and it includes a blank xmlns tag with every element. How do I tell it that each element should have it's own line in the XML document and how do I tell it to use the same namespace as the rest of the document? I know I could just explicitly tell it that it should have a xmlns attribute with the correct NS, but that is the last thing I want to do. ideas?

Update - the code for the XML Writer

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.NewLineHandling = NewLineHandling.Entitize;

using (XmlWriter currentWriter = XmlWriter.Create(filePath, settings))
{
     workingXmlDocument.WriteTo(currentWriter);
     currentWriter.Flush();
} // using (XmlWriter xw = XmlWriter.Create(FilePath))

From here it is not adding new lines to the included elements from the above code.

Upvotes: 2

Views: 337

Answers (1)

Jeff Yates
Jeff Yates

Reputation: 62397

I would write the loop as follows, providing the namespace. This should create the nodes as you want them.

foreach (var now in targetDirectory)
{
    now.Add(new XElement(
        wixNS + "Directory",
        new XAttribute("Id", fileVariable.Directory.Name));
}

I am presuming here that wixNS is an instance of XNamespace, such as:

XNamespace wixNS = "http://schemas.microsoft.com/wix/2003/01/wi";

I am not sure why the indenting is not working.

Upvotes: 2

Related Questions