Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
Conservar etiquetas HTML en valores de nodos secundarios XML al usar XMLSerializer

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 selection

Sin 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, "&lt;");//replace the "<" with "&lt;" var encoded_title = encoded_title_lt.replace(/>/g, "&gt;");//replace the ">" with "&gt;" xml_dom.getElementsByTagName("Title")[0].childNodes[0].nodeValue = encoded_title //Add the encoded string to the node, replacing what's there

Tenga 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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda