简体   繁体   中英

Using jQuery and JavaScript, how do I distinguish between two XML levels that have the same Name attr?

So this is an example Documentation.XML file of what I am trying to parse using jQuery

<DocPortal Version="">
    <Folder Name="Sample Drawings" User="*">
        <File Type="TILES" Name="Sample1" FileName="Sample1.zip"/>
    </Folder>
    <Folder Name="Sample Site Information" User="*">
        <Folder Name="SampleInnerFolder1" User="*">
            <File Type="PDF" Name="Sample1" FileName="Sample1.pdf"/>
            <File Type="PDF" Name="Sample2" FileName="Sample2.pdf"/>
        </Folder>
        <Folder Name="SampleInnerFolder2" User="*">
            <File Type="PDF" Name="Sample1" FileName="Sample1.pdf"/>
            <File Type="PDF" Name="Sample2" FileName="Sample2.pdf"/>
        </Folder>
        <File Type="PDF" Name="Sample1" FileName="Sample2.pdf" QR=""/>
        <File Type="PDF" Name="Sample2" FileName="Sample2.pdf" QR=""/>
    </Folder>
</DocPortal>

When I perform the following code, I get a list of all Folder names in both levels

$.get(lDocumentationFilePath , function(data){
    $('#content').empty();
    $(data).find('Folder').each(function(){
        var $Folder = $(this);
        console.log($Folder.attr('Name'));
    });
});

What I want is just a list of each of the top-level Folder Names. So just "Sample Drawings" and "Sample Site Information".

Any ideas?

You need to use children() instead of find() to only get the top level descendants.

$(data).children('Folder').each(function(){
    var $Folder = $(this);
    console.log($Folder.attr('Name'));
});

Given a jQuery object that represents a set of DOM elements, the .children() method allows us to search through the children of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while .find() can traverse down multiple levels to select descendant elements (grandchildren, etc.) as well, reference .

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