Search code examples
c#xmlxmlwriter

How to format XML using WriteStartDocument WriteStartElement WriteAttributeString in C#?


I want the XML in format like:

<?xml version="1.0" encoding="UTF-8"?>
<ftc:A xmlns="urn:oecd:ties:stfatypes:v1" xmlns:ftc="urn:oecd:ties:a:v1" xmlns:xsi="http://www.a.com/2001/XMLSchema-instance" version="1.1" xsi:schemaLocation="urn:oecd:ties:a:v1 aXML_v1.1.xsd">
    <ftc:b>
        <z issuedBy = "s">1</z>
        <x>CO</x>
    </ftc:b>
</ftc:A>

I forget the attribute issuedBy, I've had trouble writing the attributes whit the methods:

writer.WriteStartDocument ();
writer.WriteStartElement ();
writer.WriteAttributeString ();
writer.WriteElementString ();

I just need the example in C# please :)


Solution

  • Like t3chb0t said, the newer classes like XDocument would make this easier. But assuming you need to use XmlWriter, here's how you can do it:

    const string rootNamespace = "urn:oecd:ties:stfatypes:v1";
    const string ftcNamespace = "urn:oecd:ties:a:v1";
    const string xsiNamespace = "http://www.a.com/2001/XMLSchema-instance";
    
    var settings = new XmlWriterSettings
    {
        Indent = true,
    };
    
    var sb = new StringBuilder();
    using (var writer = XmlWriter.Create(sb, settings))
    {
        writer.WriteStartDocument();
        writer.WriteStartElement("ftc", "A", ftcNamespace);
        writer.WriteAttributeString("xmlns", "", null, rootNamespace);
        writer.WriteAttributeString("xmlns", "ftc", null, ftcNamespace);
        writer.WriteAttributeString("xmlns", "xsi", null, xsiNamespace);
        writer.WriteAttributeString("version", "1.1");
        writer.WriteAttributeString("schemaLocation", xsiNamespace, "urn:oecd:ties:a:v1 aXML_v1.1.xsd");
        writer.WriteStartElement("b", ftcNamespace);
        writer.WriteElementString("z", rootNamespace, "1");
        writer.WriteElementString("x", rootNamespace, "CO");
        writer.WriteEndElement();
        writer.WriteEndElement();
        writer.WriteEndDocument();
    }