Create new file discarding current XML lines C #

0

I have an XML file like this:

<?xml version="1.0" encoding="UTF-8"?>
<Message>
   <MessageId>
      <ServiceId>SolicitaLogon</ServiceId>
      <Version>1.0</Version>
      <MsgDesc>Solicitação do Desafio de Logon</MsgDesc>
      <Code>200601001987</Code>
      <FromAddress>TJ</FromAddress>
      <ToAddress>PGE</ToAddress>
      <Date>2011-10-20</Date>
   </MessageId>
   <MessageBody>
      <Resposta>
         <Mensagem>
            <Codigo>0</Codigo>
            <Descricao>Mensagem processada com sucesso</Descricao>
         </Mensagem>
         <Desafio>4557830751418350620</Desafio>
      </Resposta>
   </MessageBody>
   <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
   </Signature>
</Message>

I want to read this file by discarding what is between the response tag. I'm doing this, I appreciate it if there is a better way:

//carrega o mesmo arquivo, e adiciona o desafio criptografado
XmlDocument x = new XmlDocument();
string CaminhoCompletoArquivoConfirmacao = PathPadrao + "confirmaLogon.xml";
x.Load(CaminhoCompletoArquivoConfirmacao);
var todosOsNos = x.SelectNodes("//*");
for (int i = 0; i < todosOsNos.Count; i++)
{
  var element = todosOsNos[i];
  string ElementoCompleto = element.Name + element.InnerText;

  if (element.Name == "Resposta" && element.Name == "Mensagem" && element.Name != "Codigo" && element.Name != "Descricao")
  {
    EscreveXMLIndividual(ElementoCompleto, "ConfirmaLogonNovo.xml");
  }

}
    
asked by anonymous 16.06.2018 / 06:29

1 answer

1

Maybe you can another way for this. Since you want to simply manipulate xml , a xslt file is well suited for this.

The file would have this structure:

<?xml version="1.0"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

    <xsl:output indent="yes" />

    <xsl:template match="/">
        <!-- aqui crio um node Resposta -->
        <xsl:element name= "Resposta">
            <!-- aqui copio o conteúdo de do node Reposta, com seu caminho completo -->
            <xsl:copy-of select="/Message/MessageBody/Resposta/node()"/>
            </xsl:copy-of>
        </xsl:element>

    </xsl:template>
</xsl:stylesheet>

To process xslt you can use code like this:

System.Xml.Xsl.XslCompiledTransform xlst = new System.Xml.Xsl.XslCompiledTransform();
xlst.Load(@"c:\meuArquivoXslt.xslt");

System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter("resultado.xml", null);
xmlWriter.Formatting = System.Xml.Formatting.Indented;
xlst.Transform(CaminhoCompletoArquivoConfirmacao, xmlWriter);

xmlWriter.Close();
    
16.06.2018 / 14:48