Estoy trabajando con la API de blob en la última versión de Chrome y me gustaría agregar el siguiente DOM XML a una nueva URL de objeto vacía:
<root> <Title> <H1>A Title</H1> <H2>A Subtitle</H2> Some text or other elements<BR/> </Title> </root>Esta pieza de XML es seleccionada por el usuario con su mouse desde un DIV de contenido editable. Luego convierto esa selección en un DOM XML así:
var n_parser = new DOMParser; //new parser var small_xml_string = "<root>" + window.getSelection().toString() + "</root>"; //add a root node var small_xml_obj = n_parser.parseFromString(small_xml_string.replace(/\n/g, ""), "text/xml"); //convert user selection to string then to an XML DOM while removing some expected newlines below the selectionSin embargo, DOMParser no puede convertir ningún nodo a XML que tenga etiquetas HTML, lo que da como resultado el siguiente DOM:
<root> </Title> </root>Intenté escapar de las entidades HTML pero el analizador aún se comporta igual. Este fue el código que creé para tratar de tratar con entidades:
var unencoded_title = small_xml_string.toString().substring( small_xml_string.toString().indexOf("<Title>") + 7, small_xml_string.toString().indexOf("</Title>") );//Find the string between the title tags var encoded_title_lt = unencoded_title.replace(/</g, "<");//replace the "<" with "<" var encoded_title = encoded_title_lt.replace(/>/g, ">");//replace the ">" with ">" xml_dom.getElementsByTagName("Title")[0].childNodes[0].nodeValue = encoded_title //Add the encoded string to the node, replacing what's thereTenga en cuenta que "xml_dom" es un DOM listo que se ve así:
<root> <Title>Example </Title> </root>Sin embargo, el DOM resultante es exactamente el mismo que si hubiera pasado las etiquetas HTML. Los usuarios agregarán etiquetas HTML como saltos de línea y superíndices a la entrada. ¿Cómo puedo procesar etiquetas HTML en la entrada del usuario, listas para pasar a la API de blob?
Su problema está en getSelection().toString() esto devolverá el contenido de texto de la selección real. Lo que quieres es Range.cloneContents() , que obtiene una copia de la estructura DOM:
document.querySelector("button").onclick = evt => { const sel = getSelection(); const range = sel.rangeCount && sel.getRangeAt(0); const content = range.cloneContents?.(); const xml = new DOMParser().parseFromString(`<root> <Title/> </root>`, "text/xml"); xml.querySelector("Title").append(content||""); console.log(new XMLSerializer().serializeToString(xml)); }; Select the content below: <H1>A Title</H1> <H2>A Subtitle</H2> Some text or other elements<BR/> <button>log</button>