Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
How to parse and append to XML file a new content?

I have an hardcoded XML file I need to parse and append some content.

This is the file:

<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="PropertiesComponent"><![CDATA[{
  "keyToString": {
    "RunOnceActivity.OpenProjectViewOnStart": "true"
  }
}]]></component>
</project>

My Target is to convert it to:

<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="PropertiesComponent"><![CDATA[{
  "keyToString": {
    "RunOnceActivity.OpenProjectViewOnStart": "true",
    "test": 5
  }
}]]></component>
</project>

I have the following JS code to do so:

const path = require('path');

const fs = require('fs-extra');
const xml2js = require('xml2js');

const xmlFilePath = path.join(__dirname, './resource.xml');
const xmlFileDestPath = path.join(__dirname, './resource-new.xml');

(async () => {
    const xmlContent = await fs.readFile(xmlFilePath, 'utf-8').catch(() => '');
    const parsedXml = await xml2js.parseStringPromise(xmlContent);

    const objectToAppend = parsedXml['project']['component'][0]['_'];
    const parsedObject = JSON.parse(objectToAppend);
    const parsedKeyToString = parsedObject['keyToString'];

    const newObject = { ...parsedKeyToString, test: 5 };

    parsedXml['project']['component'][0]['_'] = JSON.stringify({ keyToString: newObject });

    const builder = new xml2js.Builder({
        xmldec: { version: '1.0', encoding: 'UTF-8' },
        cdata: true,
    });

    const workspaceXmlFileContent = builder.buildObject(parsedXml);

    await fs.writeFile(xmlFileDestPath, workspaceXmlFileContent);
})();

But the output file is:

<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="PropertiesComponent">{"keyToString":{"RunOnceActivity.OpenProjectViewOnStart":"true","test":5}}</component>
</project>

Not exactly what I wanted. Where is my problem?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

I tried your case with xml2js and got the same error.

I fixed it by using another package xml2j-cdata This is my new test and it works just the way you want it to. Hope can help you https://codesandbox.io/s/xml2js-cdata-test-hu39jw?file=/src/index.js https://www.npmjs.com/package/xml2js-cdata

about 4 years ago · Juan Pablo Isaza Relatório

0

I could solve it by inserting a dummy value which enforces the library to use CDATA. I created dummy value that contains a character (<) which will trigger the package to use CDATA:

const path = require('path');

const fs = require('fs-extra');
const xml2js = require('xml2js');

const xmlFilePath = path.join(__dirname, './resource.xml');
const xmlFileDestPath = path.join(__dirname, './resource-new.xml');

(async () => {
    const xmlContent = await fs.readFile(xmlFilePath, 'utf-8').catch(() => '');
    const parsedXml = await xml2js.parseStringPromise(xmlContent);

    const objectToAppend = parsedXml['project']['component'][0]['_'];
    const parsedObject = JSON.parse(objectToAppend);
    const parsedKeyToString = parsedObject['keyToString'];

    const newObject = { ...parsedKeyToString, test: '<xxx>' };

    parsedXml['project']['component'][0]['_'] = JSON.stringify({ keyToString: newObject });

    const builder = new xml2js.Builder({
        xmldec: { version: '1.0', encoding: 'UTF-8' },
        cdata: true,
    });

    const workspaceXmlFileContent = builder.buildObject(parsedXml);

    await fs.writeFile(xmlFileDestPath, workspaceXmlFileContent);
})();
about 4 years ago · Juan Pablo Isaza Relatório

0

I believe you're better off trying it this way:

xml = `<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="PropertiesComponent"><![CDATA[{
  "keyToString": {
    "RunOnceActivity.OpenProjectViewOnStart": "true"
  }
}]]></component>
</project>
`
//parse the xml
domdoc = new DOMParser().parseFromString(xml, "text/xml")
//locate the right element
result = domdoc.evaluate('//component', domdoc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

//extract the CDATA
let target = result.snapshotItem(0).childNodes[0].textContent
//parse the content into JSON
jobj = JSON.parse(target)
//create a new entry
newentry = { ...jobj.keyToString, "Test": 5};
//modify the JSON object
jobj.keyToString=newentry

//insert the modified entry into the JSON and stringify it
result.snapshotItem(0).childNodes[0].textContent=JSON.stringify(jobj);
console.log(domdoc.querySelector('project').outerHTML)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda