.NET
Microsoft Technologies based on the .NET software framework.
3,385 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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();
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 );