本文介绍了使用 javascript 打印漂亮的 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,它表示我想要漂亮打印的非缩进 XML.例如:

应该变成:

大多数 XSLT 处理器(.NET XslCompiledTransform、Saxon 6.5.4 和 Saxon 9.0.0.2、AltovaXML)产生想要的结果:

I have a string that represents a non indented XML that I would like to pretty-print. For example:

<root><node/></root>

should become:

<root>
  <node/>
</root>

Syntax highlighting is not a requirement. To tackle the problem I first transform the XML to add carriage returns and white spaces and then use a pre tag to output the XML. To add new lines and white spaces I wrote the following function:

function formatXml(xml) {
    var formatted = '';
    var reg = /(>)(<)(/*)/g;
    xml = xml.replace(reg, '$1
$2$3');
    var pad = 0;
    jQuery.each(xml.split('
'), function(index, node) {
        var indent = 0;
        if (node.match( /.+</w[^>]*>$/ )) {
            indent = 0;
        } else if (node.match( /^</w/ )) {
            if (pad != 0) {
                pad -= 1;
            }
        } else if (node.match( /^<w[^>]*[^/]>.*$/ )) {
            indent = 1;
        } else {
            indent = 0;
        }

        var padding = '';
        for (var i = 0; i < pad; i++) {
            padding += '  ';
        }

        formatted += padding + node + '
';
        pad += indent;
    });

    return formatted;
}

I then call the function like this:

jQuery('pre.formatted-xml').text(formatXml('<root><node1/></root>'));

This works perfectly fine for me but while I was writing the previous function I thought that there must be a better way. So my question is do you know of any better way given an XML string to pretty-print it in an html page? Any javascript frameworks and/or plugins that could do the job are welcome. My only requirement is this to be done on the client side.

解决方案

From the text of the question I get the impression that a string result is expected, as opposed to an HTML-formatted result.

If this is so, the simplest way to achieve this is to process the XML document with the identity transformation and with an <xsl:output indent="yes"/> instruction:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

    <xsl:template match="node()|@*">
      <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
      </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

When applying this transformation on the provided XML document:

<root><node/></root>

most XSLT processors (.NET XslCompiledTransform, Saxon 6.5.4 and Saxon 9.0.0.2, AltovaXML) produce the wanted result:

<root>
  <node />
</root>

这篇关于使用 javascript 打印漂亮的 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 09:15