How to create an XML document in native editor (JavaScript)?

What are solutions for creating XML in native response?

My goal is to create XML content and serialize it to a local file using the-native-fs reaction

For reading XML I use DOMParser.

const DOMParser = require('xmldom').DOMParser;

What is available for writing XML under a responsive environment?

Thanks in advance,

+4
source share
1 answer

Nothing...

DOMParser found in xmldom can also create XML

See: xmldom

https://www.npmjs.com/package/xmldom

const DOMParser = require('xmldom').DOMParser;
const XMLSerializer = require('xmldom').XMLSerializer;

// Append a child element
function appendChild(xmlDoc, parentElement, name, text) {
  let childElement = xmlDoc.createElement(name);
  if (typeof text !== 'undefined') {
    let textNode = xmlDoc.createTextNode(text);
    childElement.appendChild(textNode);
  }
  parentElement.appendChild(childElement);
  return childElement;
}

export function exportToXmlDoc(myPlan) {

  // documentElement always represents the root node
  const xmlDoc = new DOMParser().parseFromString("<doc></doc>");
  const rootElement = xmlDoc.documentElement;
  const folderElement = appendChild(xmlDoc, rootElement, 'folder');
  appendChild(xmlDoc, folderElement, 'version', 0);
  const planElement = appendChild(xmlDoc, folderElement, 'plan');
  appendChild(xmlDoc, planElement, 'name', 'Eddie');

  const xmlSerializer = new XMLSerializer();
  const xmlOutput = xmlSerializer.serializeToString(xmlDoc);

  console.log("xmlOutput:", xmlOutput);

  return xmlOutput;
}

xmlOutput:

<doc>
    <folder>
        <version>0</version>
        <plan>
              <name>Eddie</name>
        </plan>
    </folder>
</doc>
+3
source

Source: https://habr.com/ru/post/1661504/


All Articles