Create new file by discarding current XML lines C#

Asked

Viewed 24 times

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 discarding what is between the answer tag. I am doing so, but I appreciate 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");
  }

}

1 answer

1

Maybe you can another way to it. How do you want to simply manipulate the xml, an archive xslt is well suited to it.

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 a code like this for example:

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

Browser other questions tagged

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