How to convert XML String to Y.XmlFragment?

Having a XML in string format <a>b</a> how do I create a XMLFragment with that string content?

or, having an existing XmlFragment how to I create another XmlFragment with the same content?

1 Like

so I guess there’s no way to convert XML string to Y.XML?

You can try to parse XML by some XMLParser, and use insert API to create an XmlFragment.

The codes are like:

const doc = new Y.Doc();
const xmlFragment = doc.get('xml', Y.XmlFragment);

const xml = parseXML(xmlString);
const nodeToType = new Map();
traverse(xml, function(node, parentNode) {
  let type = null;
  if (isText(node)) {
    type = new Y.XmlText(node.text);
  } else {
    type = new Y.XmlElement(node.tagName);
  }
  nodeToType.set(node, type);
  const parentType = nodeToType.get(parentNode);
  parentType.insert(parentType.length, type);
})
1 Like

Tha’s clever, thanks @vivaxy I’ll try it