nodejs elementtree npm xml parsing and merging

一笑奈何 提交于 2019-12-01 13:55:22
Antonio Narkevich

Finally I was able to make it working with current lib. Please see my comments:

'use strict';

const et = require('elementtree');
const path = require('path');
const fs = require('fs');

function populateXmlTemplate(id) {
	//Please use path.join to make it cross-platform
	var template_XML = path.join(__dirname, 'template.xml');
	var sample_XML = path.join(__dirname, 'sample.xml');
	var new_xml = path.join(__dirname, 'new.xml');

	var data = fs.readFileSync(template_XML).toString();
	var data1 = fs.readFileSync(sample_XML).toString();

	var etree = et.parse(data);
	var etree1 = et.parse(data1);

	var root = etree.getroot();

	var placeholder = root.find('./Profile');
	root.remove(placeholder);

	var profiles = etree1.findall('./Profile'); // Find the required profile.
	for (var i = 0; i < profiles.length; i++) {
		//If I get it right, it shouldn't be hardcoded
		if (profiles[i].get('id') == id) {
			var tmppro = profiles[i];
		}
	}

	//After you removed the placeholder the number of children decreased
	//So it should be 2, not 3.
	//Also etree doesn't have insert method, please call root.insert
	root.insert(2, tmppro);

	//You have been writing the document a bit incorrectly.
	var resultXml = etree.write();
	fs.writeFileSync(new_xml, resultXml);
}

populateXmlTemplate('profile2');

module.exports = {populateXmlTemplate};

But you're right, the documentation is not good. It's mostly missing. So mostly I simply have been debugging it to see the available methods, also there are some tests in the lib repo.

There are other modules to work with js. Please see this answer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!