I am using cheerio to mutate a xml file in node. I am inserting the node/element <target>
after <source>
which works with the insertAfter()
api in oldEl.translation.insertAfter(msgSourceEl);
.
However, I loose my indention:
<trans-unit id="title" datatype="html">
<source>Login</source><target>iniciar sesión</target>
Is it possible, or is there a way, to indent the newly inserted <target>iniciar sesión</target>
underneath the <source>
element?
It is possible to use xml-beautifier
to achieve the human-readable indented XML
import beautify from 'xml-beautifier';
const HumanXML = beautify(XML);
console.log(HumanXML); // => will output correctly indented elements
Cheerio
:In the following example we will be using xml2js
to manipulate the XML as a JSON and then build it back to the original XML format
var xml2js = require('xml2js');
var xml = "<trans-unit id=\"title\" datatype=\"html\"><source>Login</source></trans-unit>"
xml2js.parseString(xml, function (err, result) {
result["trans-unit"].target=["iniciar sessión"]
var builder = new xml2js.Builder();
var xml = builder.buildObject(result);
console.log(xml)
});
Final Output :
<trans-unit id="title" datatype="html">
<source>Login</source>
<target>iniciar sessión</target>
</trans-unit>
I am sure you are doing this as part of a loop, so it shouldn't be hard to extrapolate the example to make it work . I suggest using underscore
for the usual (each, map, reduce, filter...)