How to display xml in javascript?

As stated in this question, it just eluded my memory of how to display xml in javascript, I want to display some source xml in a div on the page, which is next to the processed xml result in another div.

It is impossible to remember if there was a javascript escape equivalent for converting objects on the client

Note : xml files are executed as is on the server, so I need a solution for the client side

Note : the main problem is that XML does not display correctly in most browsers, all brackets and attributes disappear, leaving you with text that is not like xml

+5
source share
7 answers

If you want your browser to display yours XMLas XMLit should be in it own document, for example, iframeor frame. DIVwon't do the job!

In addition, in the header of the HTTPrequest serving iframeyou should send Content-Type: text/xml, so the browser can understand what the content is XML.

But if you really need to see it in the DIV, you will need to create a rendering function XML XML2HTML. You can use the tag HTML PREif your line is XMLalready formatted (line breaks and tabs). In this case, you will have to replace <with &gt;in the line XML.

: The browser XML HTML . , .

+7

XML Ajax textarea. .

+12

:

<script type="text/javascript">
<!--
    function xml_to_string(xml_node)
    {
        if (xml_node.xml)
            return xml_node.xml;
        else if (XMLSerializer)
        {
            var xml_serializer = new XMLSerializer();
            return xml_serializer.serializeToString(xml_node);
        }
        else
        {
            alert("ERROR: Extremely old browser");
            return "";
        }
    }

    // display in alert box
    alert(xml_to_string(my_xml));

    // display in an XHTML element
    document.getElementById("my-element").innerHTML = xml_to_string(my_xml);
-->
</script>
+7

JavaScript ...

function insertLiteral(literalString, targetElement)
{
    var textNode = document.createTextNode(literalString);
    targetElement.appendChild(textNode)
    return textNode;
}

// test it (for the example, I assume #targetDiv is there but empty)
var xmlString = "<this><is_some><xml with='attributes' /></is_some></this>";
var targetElement = document.getElementById("targetDiv");
var xmlTextNode = insertLiteral(xmlString, targetElement);

#targetDiv CSS:

#targetDiv {
  font-family: fixed;
  white-space: pre;
}
+6

, , HTML : <, > , &, ""

Core JavaScript , .

, Prototype : http://www.prototypejs.org/api/string/escapeHTML

+3

iframe src, XML , ( , ):

<iframe src="/myapp/Document1.xml"><iframe src="/myapp/Document2.xml">

AJAX XML- HTML, - :

getElementById("myDiv").innerText = ajax.response;
+1

This is the easiest way to find XML as text on the same page for copy and paste:

var xml = document.getElementById('svg_element').innerHTML;
document.getElementById('svg_pre').innerText = xml; 
+1
source

All Articles