XmlDocument - 无法将前缀“”从“”重新定义为 'X'

XmlDocument - The prefix '' cannot be redefined from '' to 'X'

我正在这样做:

 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));

然后为了得到 XML 缩进,我这样做:

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);
}

执行 doc.Save(writer) 时出现异常。

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.

我已经尝试了所有我能找到的方法。谢谢。

您试图在命名空间中创建 Document 元素 而不是 ,但同时设置了默认命名空间。我怀疑你只是想要:

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);

或者,我强烈推荐使用 LINQ 来 XML,这使得这个和许多其他任务变得非常非常简单。