JQuery XML解析:替换标签 [英] JQuery XML parsing: Replacing Tags
问题描述
我有以下XML:
<?xml version="1.0" encoding="UTF-8" ?>
<text>
Lorem <foo>ipsum</foo> dolor sit amet.
</text>
,并尝试使用JQuery解析此XML,并将响应内的<foo>
标签替换为<b></b>
标签.结果字符串应为"Lorem <b>ipsum</b> dolor sit amet."
and am trying to parse this XML with JQuery and replace the <foo>
tags inside the response with <b></b>
tags. The resulting string should be "Lorem <b>ipsum</b> dolor sit amet."
我正在这样对XML进行GET请求:
I'm doing a GET request on the XML like this:
$.ajax({
type: "GET",
url: "response.xml",
dataType: "xml",
success: function(xml){
}
});
我已经尝试过像这样调用replaceWith函数:
I've already tried calling the replaceWith function like this:
$(xml).find("foo").replaceWith(function(){
return "<b>" + $(this).text() + "</b>";
});
但是这将完全从xml响应中删除文本.有什么我想念的吗?
But this will remove the text from the xml response completely. Is there something I'm missing?
Firebug显示以下错误:
Firebug shows the following error:
this [0] .innerHTML未定义
this[0].innerHTML is undefined
推荐答案
我建议您使用Web浏览器的XML DOM,而不要滥用用于处理HTML的jQuery.将XML解析为DOM的方法如下:
I'd recommend you use the XML DOM of your web browser rather than abuse jQuery, which was made to handle HTML. Here's how you can parse XML into a DOM:
var xmlDoc;
if (window.DOMParser)
{
var parser = new DOMParser();
xmlDoc = parser.parseFromString(xml, "text/xml");
}
else // Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xml);
}
// Now do the tedious DOM manipulations on xmlDoc
var foos = xmlDoc.getElementsByTagName('foo');
for (var i = 0; i < foos.length; i++)
{
var oldElem = foos[i];
var replacement = xmlDoc.createElement("b");
replacement.appendChild(xmlDoc.createTextNode(oldElem.childNodes[0].nodeValue));
oldElem.parentNode.replaceChild(replacement, oldElem);
}
修改
另一种可能性是,您可以使用客户端XSLT将XML转换为所需的HTML.对于这样的XSLT文档:
Another possibility is for you to use client-side XSLT to transform the XML into your desired HTML. With an XSLT document like this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/1999/xhtml">
<xsl:template match="*">
<xsl:value-of select="."/>
</xsl:template>
<xsl:template match="text">
<span>
<xsl:apply-templates/>
</span>
</xsl:template>
<xsl:template match="foo">
<b>
<xsl:apply-templates/>
</b>
</xsl:template>
</xsl:stylesheet>
您可以将示例输入转换为带有b
标签的span
.如果您有很多转换规则,则XSLT可能比一堆笨拙的DOM操作代码更具可维护性.
You can transform your sample input into a span
with b
tags. If you have lots of transformation rules, XSLT may be more maintainable than a bunch of crummy DOM manipulation code.
这篇关于JQuery XML解析:替换标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!