简体   繁体   English

如何将XML DOM元素转换为HTML DOM元素?

[英]How do I convert an XML DOM element into an HTML DOM element?

I am trying to use an XMLHTTPRequest to download an .xml file and add some of it's elements to the page as content. 我正在尝试使用XMLHTTPRequest下载.xml文件并将其某些元素作为内容添加到页面。 What I have done is to make the request, get the document, get the specific DOM elements from the xml that I want to import, use existing.appendChild(fromXML) to append the element from the xml DOM to the element in the HTML DOM. 我要做的是发出请求,获取文档,从我要导入的xml中获取特定的DOM元素,使用existing.appendChild(fromXML)将xml DOM中的元素追加到HTML DOM中的元素。

However, none of the actual tags are rendered. 但是,没有渲染任何实际的标签。 The text inside each of the tags is rendered just fine. 每个标记内的文本都可以很好地呈现。 But the tags themselves seem to be ignored. 但是标签本身似乎被忽略了。 Firebug shows the added tags in the HTML panel in light blue font rather than normal blue for other tags, but I haven't been able to figure out what that means. Firebug在HTML面板中以浅蓝色字体显示添加的标签,而不是其他标签的普通蓝色,但是我一直无法弄清楚这意味着什么。 The webkit developer tools also shows me that the tags are there (no special coloring, though), but they are not rendered properly (img and a tags don't have any effect at all, for example). 该Webkit开发人员工具还向我显示了标签在那里(尽管没有特殊的颜色),但是它们没有正确呈现(例如img和标签根本没有任何作用)。

Am I missing some conversion from XML DOM to HTML DOM? 我是否缺少从XML DOM到HTML DOM的转换?

Here is a simple version of my code with comments for brevity: 这是我的代码的简单版本,为简洁起见:

// Make xmlHTTPRequest
...

// Get items from the response xml
var items = xhr.responseXML.getElementsByTagName("item");  

// Get one item and it's children recursively
var elm = document.importNode(items[0],true);  

// Get the existing element to add the item add to  
existingDomElement = document.getElementById("demo");   

for (var i = 0; i < $(elm).children().length; i++) {  
    var child = $($(safeChild).children()[i])[0];  
    existingDomElement.appendChild(child);  
} 

Apparently, it's been done before, see this question . 显然,它已经完成了,请参见此问题 That poster's code seems to work, but he wants something more elegant and concise. 该张贴者的代码似乎有效,但是他想要更优雅简洁的内容。 He seems to be one step ahead of you in that at least. 至少在这方面他似乎比您领先一步。

But the only suggestion there is to serialize the whole thing to text, and then parse it in the current tree — which might not necessarily work in your case anyway, since XML might not always parse correctly as HTML... 但是唯一的建议是将整个过程序列化为文本,然后在当前树中进行解析-无论如何,这不一定对您有用,因为XML不一定总是正确地解析为HTML ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM