0

I need to add a line after xml declaration to process a file on an external system that rejects it if missing. I had formatted the doc by myself on creation and signing it, so I don't want to mess with formatting as corrupts the signature (it has also third-party external signed documents) .

Yes, I can open it as text, use replace "?><" by "?>\r\n<", save it, or do everything manually, but I want to do it "the XmlDocument" way.

What I have:

<?xml version="1.0" encoding="ISO-8859-1"?><LceEnvioOblig xmlns="http://www.sii.cl/SiiLce" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sii.cl/SiiLce LceEnvioOblig_v10.xsd" version="1.0">
<DocumentoEnvioOblig ID="EnvioOblig_12868626-6_76876251-1">
<Caratula>
<RutEnvia>12868626-6</RutEnvia>
<RutContribuyente>76876251-1</RutContribuyente>
<TmstFirmaEnv>2019-01-15T12:00:14-03:00</TmstFirmaEnv>
</Caratula>

What I need:

<?xml version="1.0" encoding="ISO-8859-1"?>
<LceEnvioOblig xmlns="http://www.sii.cl/SiiLce" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sii.cl/SiiLce LceEnvioOblig_v10.xsd" version="1.0">
<DocumentoEnvioOblig ID="EnvioOblig_12868626-6_76876251-1">
<Caratula>
<RutEnvia>12868626-6</RutEnvia>
<RutContribuyente>76876251-1</RutContribuyente>
<TmstFirmaEnv>2019-01-15T12:00:14-03:00</TmstFirmaEnv>
</Caratula>

Relevant code:

    signedXml.ComputeSignature();

    XmlElement xmlDigitalSignature = signedXml.GetXml();

    xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
    var dec = xmlDoc.CreateXmlDeclaration("1.0", Constantes.SaveEncoding.EncodingName,"no");


    using (var sw = new StreamWriter(salida, false, Constantes.SaveEncoding))
    {
        xmlDoc.Save(sw);
    }

Note I am not using indentations and PreserveWhitespace has not worked fine for me.

Any suggestions or best way to do it?

Jorge Rojas
  • 485
  • 3
  • 10
  • 1
    There's no code there that inserts the declaration anywhere ([for example](https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmldocument.createxmldeclaration?view=netframework-4.7.2#examples)), so you're probably just getting the default behavior. When inserting the node explicitly, you should also be free to insert a whitespace node afterwards. – Jeroen Mostert Jan 15 '19 at 15:41
  • Thank you! I got it working. The estándar method created the declaration using the stream info, so I added it manually like this: xmlDoc.InsertAfter(xmlDoc.CreateWhitespace(Environment.NewLine), xmlDoc.ChildNodes[0]); – Jorge Rojas Jan 15 '19 at 22:07

0 Answers0