在HTML页面中显示XML代码可能很困难。 XML标记将被识别为HTML标记,因此它们不会按预期显示。 转义尖括号<>工作,但然后xml代码将全部显示为黑色,难以阅读。有没有办法在HTML页面中设置样式化XML代码,就像我在XML编辑器中读取它一样?
答案 0 :(得分:1)
这是我的 javascript 函数,它将样式更改为xml-key-words !! (不幸的是它没有缩进xml) 它接受纯XML文本作为输入,并返回HTML样式代码,xml作为文本,着色 编辑器中具有不同颜色的XML关键字。
function stylizeXML(xml)
{
xml = xml.replace(/>/g,">");
xml = xml.replace(/</g,"<");
xml = xml.replace(/\>\</g, "> <br> <"); // >< becomes > <br> <
var greens=xml.match(/<(\S+\s+)+[\S]+\=\"[^>]+>/g); // ...=
for (i=0; i<greens.length; i++)
{
greens=xml.match(/\s+\S+\=\"/g);
for (i=0; i<greens.length; i++)
{
green = greens[i];
green = green.replace(/\=\"/g, '=</span>"');
attributes = green.match(/\s+\S+\=<\/span>\"/g);
for(j=0; j<attributes.length; j++)
{
attribute2 = "<span class='color_green'>"+attributes[j];
green = green.replace(attributes[j], attribute2);
}
xml = xml.replace(greens[i], green);
}
}
var blues=xml.match(/\<(.*?)\>/g); // < ... >
for (i=0; i<blues.length; i++)
{
blue = blues[i];
blue = blue.replace("</","");
blue = blue.replace("<","");
blue = blue.replace(">","");
if (blues[i].match(/^\<\//))
// </ ... >
{xml = xml.replace(blues[i], "<span class='color_orange'></</span><span class='color_blue'>"+blue+"</span><span class='color_orange'>></span>");} // </
else
// < ... >
{xml = xml.replace(blues[i], "<span class='color_orange'><</span><span class='color_blue'>"+blue+"</span><span class='color_orange'>></span>");}
}
var reds=xml.match(/\=<\/span>(\s*)\"(.*?)\"/g); // ="..."
for (i=0; i<reds.length; i++)
{
red = reds[i];
red = red.replace("=</span>","");
xml = xml.replace(reds[i], "=</span><span class='color_red'>"+red+"</span>");
}
return xml;
}
这里是相关的CSS:
<style type="text/css">
.color_orange
{color :rgb(255,96,24);}
.color_blue
{color :blue;}
.color_red
{color :rgb(234, 49, 176);}
.color_green
{color : rgb(72,150,163);}
</style>