Hi @TRAIAN MACAVEIU , Welcome to Microsoft Q&A,
You want to add the namespace prefix nsSAFT: to each node to ensure that the entire XML structure uses that prefix. To achieve this, you need to explicitly add the namespace prefix when generating the XML file. To generate XML files with a specific namespace and prefix, you can use the XmlSerializerNamespaces class to specify the namespace and prefix.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
namespace xx
{
public class AuditFile
{
[XmlElement(Namespace = "mfp:anaf:dgti:d406:declaratie:v1")]
public Header Header { get; set; }
}
public class Header
{
public string AuditFileVersion { get; set; }
public string AuditFileCountry { get; set; }
}
internal class Program
{
static void Main(string[] args)
{
AuditFile doc = new AuditFile();
Header header = new Header();
// Fill with data
header.AuditFileVersion = "1.0";
header.AuditFileCountry = "RO";
doc.Header = header;
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add("nsSAFT", "mfp:anaf:dgti:d406:declaratie:v1");
namespaces.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
XmlSerializer x = new XmlSerializer(typeof(AuditFile));
// Configure XmlWriter to add namespace prefixes
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create(@"C:\Users\Administrator\Desktop\demo.xml", settings))
{
writer.WriteStartElement("nsSAFT", "AuditFile", "mfp:anaf:dgti:d406:declaratie:v1");
writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
writer.WriteAttributeString("xsi", "schemaLocation", null, "urn:StandardAuditFile-Taxation-Financial:RO schema.xsd");
// Serialize the whole AuditFile object
x.Serialize(writer, doc, namespaces);
writer.WriteEndElement();
}
}
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.