Skip to content

Instantly share code, notes, and snippets.

@Convicted202
Forked from husa/xml2react.js
Created July 19, 2016 14:12
Show Gist options
  • Save Convicted202/f132e0874c2f3ae89d41b797fc782485 to your computer and use it in GitHub Desktop.
Save Convicted202/f132e0874c2f3ae89d41b797fc782485 to your computer and use it in GitHub Desktop.
XML to React Component
const xml = `
<XMLText class="yeah-attributes">
regular text
<XMLBold>
bold text
</XMLBold>
another text
</XMLText>
`;
// Some simple components
class Text extends React.Component {
render () {
return (
<div className={this.props.class}>{this.props.children}</div>
);
}
}
class Bold extends React.Component {
render () {
return (
<b>{this.props.children}</b>
);
}
}
const XMLNodeToReactComponentMap = {
'XMLText': Text,
'XMLBold': Bold
};
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xml, 'text/xml');
function processChildren (children) {
return Array.from(children.length ? children : []).map(
(node, i) => {
// return if text node
if (node.nodeType === 3) return node.nodeValue;
// collect all attributes
let attributes = Array.from(node.attributes).reduce((attrs, attr) => {
attrs[attr.name] = attr.value;
return attrs;
}, {});
// create React component
return React.createElement(XMLNodeToReactComponentMap[node.nodeName], {
...attributes,
key: i
}, processChildren(node.childNodes));
});
}
// root component
class XMLtoReact extends React.Component {
render () {
return (
<div>
{processChildren(Array.from(xmlDoc.childNodes))}
</div>
);
}
}
@CarineB
Copy link

CarineB commented Aug 18, 2019

test

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment