简体   繁体   中英

Retrieving tags from XML

I'm trying with jQuery to retrieve the contents of an xml node that contains < ul> and < li> information. The problem I'm having is directly translating that into html, retaining the same structure.

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() );
                });
            });

later:

$('#answer').click(function(){
                if(sentinal !== undefined){
                    $('#question').html( answers[sentinal] );
                }
            });

What's contained in contents seems only to be the 1 and 2, without any < li> or < ul> tags.

Any thoughts on how I might keep the structure of the node?

Try

// 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 takes a DOM sub-tree from one document, such as an XML document received via XHR, and creates a structural copy in another document, such as an HTML document.

document.importNode

Summary

Creates a copy of a node from an external document that can be inserted into the current document.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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