Search code examples
c#xmlxmlwriter

C# XML writer - Which types/objects to use?


Intro: Hi fellow coders; I created a project to create XML files to automate filecreation with certain settings.

Issue: my knowledge isn't sufficient to recreate this. I can't find the right information on two questions;

A. How to create an element inside an element (using a second writestartelement closes the first one);

B. On line 3 there's an element which I do not recognise. Can anybody tell me which type I should be looking for on the net?

<userEnvironmentSettings>
    <conditions>
        <ref n="Printer - PR123456.xml" />
    </conditions>
</userEnvironmentSettings>

Current code (Will keep this up to date)

                writer.WriteStartElement("userEnvironmentSettings");
                writer.WriteStartElement("conditions");
                writer.WriteAttributeString("ref n", "Printer - " + printerName + ".xml\"");
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.Flush();

Result: $exception as per a whitespace cannot be set inside Attributestring.


Solution

  • You need an element called ref with an attribute called n. What you've tried to do is create an attribute called ref n within the conditions element, which is not allowed (as it contains whitespace) and is not what you want. So this would work:

    writer.WriteStartElement("userEnvironmentSettings");
    writer.WriteStartElement("conditions");
    writer.WriteStartElement("ref");
    writer.WriteAttributeString("n", "Printer - PR123456.xml");
    writer.WriteEndElement();
    writer.WriteEndElement();
    writer.WriteEndElement();
    

    However, unless you have good reason I'd strongly suggest you don't use XmlWriter directly. There are much easier, higher-level APIs you can use. For example:

    var doc = new XDocument(
        new XElement("userEnvironmentSettings",
            new XElement("conditions",
                new XElement("ref",
                    new XAttribute("n", "Printer - PR123456.xml")
                ))));
    doc.Save(fileName);