我正在尝试使用 jQuery 检索包含
- 和
- 信息的 xml 节点的内容。我遇到的问题是直接将其翻译成 html,并保留相同的结构。
XML:
<question num="18"> <q>JOGs are produced in what two formats? What is the major difference?</q> <ans>JOG (Air) and JOG (Ground); the topographical information is identitcal on both, but the ground version shows elevations and contour in meters and the air version shows them in feet. Both versions emphasize airlanding facilities, but the air version has additional symbols to identify aids and obstructions to air navigation. Each version is identified in the lower margin as either Joint Operations Graphic (Air) or Joint Operations Graphic (Ground).</ans> <ref>(para 2-6b(4))</ref> </question> <question num="19"> <q>What are some examples of "special" militar maps?</q> <ans>Maps designed specifically to show one or more of the following: <ul> <li>Drainage characteristics</li> <li>Climate</li> <li>Coasts and landing beaches</li> <li>Urban areas</li> <li>Electric power</li> <li>Fuels</li> <li>Water Resources</li> <li>Natural construction materials</li> </ul> </ans> <ref>(para 2-6b(8))</ref> </question>
JavaScript:
$.get("landnav.xml",{},function(xml){ $('question', xml).each(function(){ questions.push( $(this).find('q').text() ); answers.push( $(this).find('ans').contents() ); }); });
后来:
$('#answer').click(function(){ if(sentinal !== undefined){ $('#question').html( answers[sentinal] ); } });
contents里面好像只有1和2,没有
< li>
或< ul>
标签。关于如何保留节点结构的任何想法?
最佳答案
尝试
// Isolate the XML.
var xmlNode = $(this).find('node');
// Convert the XML structurally to HTML.
// The (true) causes a deep copy.
var htmlFromXml = document.importNode(xmlNode[0], true);
// Append the resulting HTML to the DOM.
$(htmlFromXml).appendTo($('#content'));
document.importNode
从一个文档(例如通过 XHR 接收的 XML 文档)中获取 DOM 子树,并在另一个文档(例如 HTML 文档)中创建结构副本。
document.importNode
Summary
Creates a copy of a node from an external document that can be inserted into the current document.
关于javascript - 从 XML 中检索标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9538593/