C# XML CDATA Save File

60 views Asked by At

Someone can help me, I had in a XMLDocument variable the following:

<autorizaciones><autorizacion><estado>aaa</estado><numeroAutorizacion>2011202</numeroAutorizacion><fechaAutorizacion>2023-11-20T10:30:14-05:00</fechaAutorizacion><ambiente>prueba</ambiente><comprobante>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;factura id="comprobante" version="1.0.0"&gt;
  &lt;infoTributaria&gt;
    &lt;ambiente&gt;2&lt;/ambiente&gt;
    &lt;tipoEmision&gt;1&lt;/tipoEmision&gt;
    &lt;razonSocial&gt;EMPRESA&lt;/razonSocial&gt;
    &lt;nombreComercial&gt;EMPRESA&lt;/nombreComercial&gt;
    &lt;ruc&gt;99999999999&lt;/ruc&gt;
    &lt;claveAcceso&gt;2011202&lt;/claveAcceso&gt;
    &lt;codDoc&gt;01&lt;/codDoc&gt;
    &lt;estab&gt;001
&lt;/estab&gt;
    &lt;ptoEmi&gt;002&lt;/ptoEmi&gt;
    &lt;secuencial&gt;000107272&lt;/secuencial&gt;
    &lt;dirMatriz&gt;AV 25 DE Y 8 VO CLLJN&lt;/dirMatriz&gt;
  &lt;/infoTributaria&gt;</comprobante><mensajes /></autorizacion></autorizaciones>

I want to save to a file in the following format:

<autorizaciones><autorizacion><estado>aaa</estado><numeroAutorizacion>2011202</numeroAutorizacion><fechaAutorizacion>2023-11-20T10:30:14-05:00</fechaAutorizacion><ambiente>prueba</ambiente><comprobante><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<factura id="comprobante" version="1.0.0">
  <infoTributaria>
    <ambiente>2</ambiente>
    <tipoEmision>1</tipoEmision>
    <razonSocial>EMPRESA</razonSocial>
    <nombreComercial>EMPRESA</nombreComercial>
    <ruc>99999999999</ruc>
    <claveAcceso>2011202</claveAcceso>
    <codDoc>01</codDoc>
    <estab>001</estab>
    <ptoEmi>002</ptoEmi>
    <secuencial>000107272</secuencial>
    <dirMatriz>AV 25 DE Y 8 VO CLLJN`your text`</dirMatriz>
  </infoTributaria></factura>]]></comprobante><mensajes /></autorizacion></autorizaciones>

I use XmlDocument docXML.Save(file) but the first format is preserve. How can i do to resolve the problem?

2

There are 2 answers

0
Alexander Petrov On

Use LINQ to XML.

using System.Xml.Linq;

var xml = XElement.Load("test.xml");

var comprobante = xml.Descendants("comprobante").First();
var value = comprobante.Value;
var cdata = new XCData(value);
comprobante.ReplaceNodes(cdata);

xml.Save("test2.xml");
0
Michael Kay On

In XSLT 3.0 it would be

<xsl:mode on-no-match="shallow-copy">
<xsl:template match="comprobante/text()">
  <xsl:copy-of select="parse-xml(.)"/>
</xsl:template>