4

What are solutions to create XML in react native?

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

For reading XML I use DOMParser.

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

What is available for writing XML under the react native environment?

Thanks in advance,

1 Answer 1

4

Never mind...

The 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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.