Edit C#XML file

Asked

Viewed 194 times

0

I’m having a little difficulty editing an xml.

I get the following xml:

<cteProc xmlns="http://www.portalfiscal.inf.br/cte" versao="3.00"> 
    <CTe CTemlns="http://www.portalfiscal.inf.br/cte">
        <infCte versao="3.00" Id="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
            <compl>Preciso inserir uma estrutura aqui!</compl>
        </infCte>
    </CTe>
</cteProc>

Among the tags <compl> </compl> I need to insert the following structure.

<ObsCont xCampo="vContainer"><xTexto>valor</xTexto></ObsCont>

I tried to edit with the following code.

var xdoc = XDocument.Load(@"C:\ArquivosXML\" + integracao.NOME + ".xml");
       xdoc.Root.Add(xdoc.Element("Cte"), xdoc.Element("compl"),
           new XElement("ObsCont",
               new XAttribute("xCampo", "vContainer"),
               new XElement("xTexto", "valor")
               )
       );
       xdoc.Save(@"C:\ArquivosXML\" + integracao.NOME + ".xml");

With the above code I can insert more between the tags <cteProc> </cteProc>

And when I enter the element ObsCont is saving <ObsCont xmlns= "" xCampo="vContainer"> the correct is <ObsCont xCampo="vContainer"> without the xmlns= "".

  • I recommend you see about serealization of xml in c#. I work with xmls like the one from CTE that you need and, to make my life easier (and much easier) I model xml in classes where I serealizo and deserealizo from xml to object and vice versa.

1 answer

0

You can put a . Replace("xmlns=\"","");

I have worked with electronic invoice and used enough replace in some specific situations.

  • O . Replace would only solve a part of my problem, I would like to handle xml correctly. I am using . Replace para resolver temporariamente o meu problema desta forma : string xml = integracao.xml;&#xA; string xmlEditado = xml.Replace("</compl>", "<ObsCont xCampo="vContainer"><xTexto>"+integracao.vl_Container+"</xTexto></ObsCont></compl>"); Xmldocument xmlDoc = new Xmldocument(); xmlDoc.Loadxml(xmlEditated); xmlDoc.Save(@"C: XML" + integration.NAME + ".xml"); integration.Path = @"C: XML"+integration.NAME+". xml";

Browser other questions tagged

You are not signed in. Login or sign up in order to post.