javascript - 从 XML 中检索标签

标签 javascript jquery html xml

我正在尝试使用 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/

相关文章:

php - jQuery 调用 PHP 文件从 mysql 数据库中获取数据?

javascript - Yii 可点击 td

javascript - JavaScript 方法中 GrailsElements 的编码

javascript - 嵌套的 {{#each}} 不工作

javascript - 使用 mergeSets Generator 函数合并集合

php - Ajax 请求无响应使用 codeigniter

javascript - 在 div 中选择非标记文本

java - 瓦丁 : CustomLayout don't generate <div> content

html - 当我调整窗口大小时 div 内容被挤压

javascript - React Native 中的 list 合并失败