从XML检索标记

时间:2012-03-02 18:36:44

标签: javascript jquery html xml

我正在尝试使用jQuery来检索包含<的xml节点的内容。 UL>和<李>信息。我遇到的问题是直接将其翻译成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] );
                }
            });

内容中包含的内容似乎只是1和2,没有任何< li>< ul>标记。

关于如何保留节点结构的任何想法?

1 个答案:

答案 0 :(得分:1)

尝试

// 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从一个文档中获取DOM子树,例如通过XHR接收的XML文档,并在另一个文档中创建结构副本,例如HTML文档。

  

<强> document.importNode

     

<强>摘要

     

从可插入当前文档的外部文档创建节点的副本。