用javascript打印XML [英] Pretty printing XML with javascript

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

问题描述

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

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

<root><node/></root>

应该成为:

<root>
  <node/>
</root>

语法突出显示不是必需的。要解决这个问题,我首先转换XML以添加回车符和空格,然后使用 pre 标记用于输出XML。为了添加新行和空格,我编写了以下函数:

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\r\n$2$3');
    var pad = 0;
    jQuery.each(xml.split('\r\n'), 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 + '\r\n';
        pad += indent;
    });

    return formatted;
}

然后我调用这样的函数:

I then call the function like this:

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

这对我来说非常好,但在我写前一个函数时我认为必须有一个更好的方法。所以我的问题是,你知道有什么更好的方法给XML字符串在html页面中漂亮打印吗?任何可以完成这项工作的javascript框架和/或插件都是受欢迎的。我唯一的要求是在客户端完成。

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.

推荐答案

从问题的文字我得到的预计字符串结果为的印象,而不是HTML格式的结果。

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

如果是这样,实现此目的的最简单方法是使用身份转换 < xsl:output indent =yes/> 指示


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

在提供的XML文档上应用此转换时:

When applying this transformation on the provided XML document:


<root><node/></root>

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

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆