I have the following situation.
Into a Java application I have a String variable named *fattura** that contains structured data extracted from an XML...so this fattura variable contains text like this:
<FatturaElettronicaBody>
<DatiGenerali>
<DatiGeneraliDocumento>
<TipoDocumento>TD01</TipoDocumento>
<Divisa>EUR</Divisa>
<Data>2015-03-16</Data>
<Numero>004600002117</Numero>
<ImportoTotaleDocumento>9.57</ImportoTotaleDocumento>
</DatiGeneraliDocumento>
</DatiGenerali>
</FatturaElettronicaBody>
Now what I need to do is to append at the beginning of the previous XML code the line that identify that this XML section is an XML document itself, this one:
<?xml version="1.0" encoding="UTF-8"?>
So the final result have to be something like this:
<?xml version="1.0" encoding="UTF-8"?>
<FatturaElettronicaBody>
<DatiGenerali>
<DatiGeneraliDocumento>
<TipoDocumento>TD01</TipoDocumento>
<Divisa>EUR</Divisa>
<Data>2015-03-16</Data>
<Numero>004600002117</Numero>
<ImportoTotaleDocumento>9.57</ImportoTotaleDocumento>
</DatiGeneraliDocumento>
</DatiGenerali>
</FatturaElettronicaBody>
So this could be done creating a new String fatturaXml variable and first append this line into it:
<?xml version="1.0" encoding="UTF-8"?>
and finally append the fattura variable content.
But exist a smarter solution? I have the fattura variable that contains the XML content, can I directly put the line before the content of the fattura variable without passing for a new variable?
It you just need to work on the string, there are simple string prepend options:
I guess someone already mentioned that.
But I think StringBuilder is a better way for string manipulation operations as Strings are immutable in Java. So it would help if you're manipulating string more than once, otherwise it might be an overkill.