Custom Namespaces and Prefix for XML file

TRAIAN MACAVEIU 91 Reputation points
2024-04-17T11:33:24.13+00:00

I have a structure in which I fill in data and I want to save it as an XML file. How can I set Namespaces and Prefix so as to obtain an XML file with the structure as in the example below? Thank you!

desired XML structure:

<?xml version="1.0" encoding="UTF-8"?>
<nsSAFT:AuditFile xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:nsSAFT="mfp:anaf:dgti:d406:declaratie:v1" xsi:schemaLocation="urn:StandardAuditFile-Taxation-Financial:RO schema.xsd">
	<nsSAFT:Header>
		<nsSAFT:AuditFileVersion>1.0</nsSAFT:AuditFileVersion><nsSAFT:AuditFileCountry>RO</nsSAFT:AuditFileCountry><nsSAFT:AuditFileRegion>RO-BH</nsSAFT:AuditFileRegion>
	</nsSAFT:Header>
</nsSAFT:AuditFile>
public class AuditFile 		
{             			
	public Header Header { get; set; } 		
}	

public class Header
{			
	public string AuditFileVersion { get; set; }
	public string AuditFileCountry { get; set; }
	public string AuditFileRegion { get; set; }
	public string AuditFileDateCreated { get; set; }
	public string SoftwareCompanyName { get; set; }
	public string SoftwareID { get; set; }
	public string SoftwareVersion { get; set; }
	public string DefaultCurrencyCode { get; set; }
	public SelectionCriteria SelectionCriteria { get; set; }
	public string HeaderComment { get; set; }
	public string SegmentIndex { get; set; }
	public string TotalSegmentsInsequence { get; set; }
	public string TaxAccountingBasis { get; set; }
}

AuditFile doc = new AuditFile();
Header header = new Header();
......
doc.Header = header;
XmlSerializer x = new System.Xml.Serialization.XmlSerializer(doc.GetType());
TextWriter writer = new StreamWriter(@"C:\document.xml");
x.Serialize(writer, doc);
writer.Close();	
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,385 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 112.2K Reputation points
    2024-04-17T14:52:01.0433333+00:00

    Using namespaces is probably a mistake.

    Try this:

    [XmlRoot( Namespace = "mfp:anaf:dgti:d406:declaratie:v1" )]
    public class AuditFile
    {
        [XmlAttribute(Namespace = "http://www.w3.org/2001/XMLSchema-instance" )]
        public string schemaLocation { get; init; } = "urn:StandardAuditFile-Taxation-Financial:RO schema.xsd";
    
        public Header Header { get; set; }
    }
    
    . . .
    
    var ns = new XmlSerializerNamespaces( );
    ns.Add( "xsi", "http://www.w3.org/2001/XMLSchema-instance" );
    ns.Add( "nsSAFT", "mfp:anaf:dgti:d406:declaratie:v1" );
    x.Serialize( writer, doc, ns );
    
    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful