I am doing this:
var xml = new XmlDocument();
xml.AppendChild(xml.CreateXmlDeclaration("1.0", Encoding.UTF8.BodyName, "yes"));
var el = (XmlElement)xml.AppendChild(xml.CreateElement("Document"));
el.SetAttribute("xmlns", "urn:iso:std:iso:20022:tech:xsd:" + SepaSchemaUtils.SepaSchemaToString(schema));
Then to get the XML indented I do:
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,
IndentChars = " ",
NewLineChars = "\r\n",
NewLineHandling = NewLineHandling.Replace
};
using (XmlWriter writer = XmlWriter.Create(sb, settings))
{
doc.Save(writer);
}
I am getting an exception when doc.Save(writer) is executed.
System.Xml.XmlException: The prefix '' cannot be redefined from '' to 'urn:iso:std:iso:20022:tech:xsd:pain.001.001.03' within the same start element tag.
I've already tried everything I could find. Thank you.
You're trying to create a Document
element not in a namespace, but set the default namespace at the same time. I suspect you just want:
String ns = "urn:iso:std:iso:20022:tech:xsd:" + SepaSchemaUtils.SepaSchemaToString(schema);
var xml = new XmlDocument();
xml.AppendChild(xml.CreateXmlDeclaration("1.0", Encoding.UTF8.BodyName, "yes"));
var el = (XmlElement) xml.AppendChild(xml.CreateElement("Document", ns));
el.SetAttribute("xmlns", ns);
Alternatively, I'd strongly recommend using LINQ to XML, which makes this and many other tasks much, much simpler.
See more on this question at Stackoverflow