2012-03-13 69 views
1

我遇到了麻煩取DOM文檔(或其中的節點)並將其序列化爲格式正確的xml。我需要這樣做,因爲我將上傳文檔的一部分的工具僅用於理解XML,而不用HTML,因爲它的不正確封閉的元素。作爲一個例子,我目前正在刮(http://studentlund.se),其中顯示我的img元素沒有被關閉的問題。從JavaScript中創建正確格式化的XML

例如,如果我執行下面的鉻合金控制檯:

$('<div>').append($('body ul:first li:last')).html() 

我會收到:

<li><a href="http://studentlund.se/feed/"><img src="http://studentlund.se/wordpress/wp- 
content/themes/studentlund/pics/rss.png" alt="RSS"></a></li> 

img元素不是封閉的,因此我的XML解析器將失敗。

如果我使用XmlSerializer:

n = $('body ul:first li:last').get(0) 
new XMLSerializer().serializeToString(n) 

我會得到相同的,格式不正確的XML:

<li><a href="http://studentlund.se/feed/"><img src="http://studentlund.se/wordpress/wp-content/themes/studentlund/pics/rss.png" alt="RSS"></a></li> 

所有我想要的是能夠在轉儲節點的RAW DOM格式正確的XML字符串,所以我可以將其與我的XML工具一起使用,這可能嗎?

回答

1

嘗試創建一個XML文檔,然後將其序列化到字符串,這樣的事情:

n = $('body ul:first li:last').get(0); 
var doc = document.implementation.createDocument('', '', null); 
doc.appendChild(n); 
var xml = new XMLSerializer().serializeToString(doc); 
+0

真棒,那工作!謝謝! – topfs2 2012-03-14 09:53:45