Ler o ficheiro XML com o javascript

o meu formato de ficheiro XML é o seguinte.

<markers>
       <marker>
          <type></type>
          <title></title>
          <address></address>
          <latitude></latitude>
          <longitude></longitude>
       <marker>
       <marker>
          <type></type>
          <title></title>
          <address></address>
          <latitude></latitude>
          <longitude></longitude>
       <marker>
    </markers>
Por favor, sugira-me Como posso ler todo o elemento "marcador". Preciso de obter o valor de todo o elemento infantil do"marcador"

Obrigado.
Author: Avinash, 2009-07-29

4 answers

O código abaixo irá converter qualquer XMLObject ou string para um objecto JavaScript nativo. Então você pode andar sobre o objeto para extrair qualquer valor que você quiser.

/**
 * Tries to convert a given XML data to a native JavaScript object by traversing the DOM tree.
 * If a string is given, it first tries to create an XMLDomElement from the given string.
 * 
 * @param {XMLDomElement|String} source The XML string or the XMLDomElement prefreably which containts the necessary data for the object.
 * @param {Boolean} [includeRoot] Whether the "required" main container node should be a part of the resultant object or not.
 * @return {Object} The native JavaScript object which is contructed from the given XML data or false if any error occured.
 */
Object.fromXML = function( source, includeRoot ) {
    if( typeof source == 'string' )
    {
        try
        {
            if ( window.DOMParser )
                source = ( new DOMParser() ).parseFromString( source, "application/xml" );
            else if( window.ActiveXObject )
            {
                var xmlObject = new ActiveXObject( "Microsoft.XMLDOM" );
                xmlObject.async = false;
                xmlObject.loadXML( source );
                source = xmlObject;
                xmlObject = undefined;
            }
            else
                throw new Error( "Cannot find an XML parser!" );
        }
        catch( error )
        {
            return false;
        }
    }

    var result = {};

    if( source.nodeType == 9 )
        source = source.firstChild;
    if( !includeRoot )
        source = source.firstChild;

    while( source ) {
        if( source.childNodes.length ) {
            if( source.tagName in result ) {
                if( result[source.tagName].constructor != Array ) 
                    result[source.tagName] = [result[source.tagName]];
                result[source.tagName].push( Object.fromXML( source ) );
            }
            else 
                result[source.tagName] = Object.fromXML( source );
        } else if( source.tagName )
            result[source.tagName] = source.nodeValue;
        else if( !source.nextSibling ) {
            if( source.nodeValue.clean() != "" ) {
                result = source.nodeValue.clean();
            }
        }
        source = source.nextSibling;
    }
    return result;
};

String.prototype.clean = function() {
    var self = this;
    return this.replace(/(\r\n|\n|\r)/gm, "").replace(/^\s+|\s+$/g, "");
}
 6
Author: BYK, 2014-12-15 17:09:09

Se obtiver isto de um servidor Web, veja jQuery . Você pode carregá-lo, usando a função Ajax load e seleccionar o nó ou texto que deseja, usando selectores.

Se não quiser fazer isto num ambiente http ou evitar usar o jQuery, por favor explique com mais detalhes.

 4
Author: Tim Büthe, 2009-07-29 10:18:14

Pode usar o programa abaixo para ler o Filho do xml acima. Vai funcionar com IE e Mozila Firefox ambos.

<script type="text/javascript">

function readXml(xmlFile){

var xmlDoc;

if(typeof window.DOMParser != "undefined") {
    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("GET",xmlFile,false);
    if (xmlhttp.overrideMimeType){
        xmlhttp.overrideMimeType('text/xml');
    }
    xmlhttp.send();
    xmlDoc=xmlhttp.responseXML;
}
else{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async="false";
    xmlDoc.load(xmlFile);
}
var tagObj=xmlDoc.getElementsByTagName("marker");
var typeValue = tagObj[0].getElementsByTagName("type")[0].childNodes[0].nodeValue;
var titleValue = tagObj[0].getElementsByTagName("title")[0].childNodes[0].nodeValue;
}
</script>
 4
Author: Jitendra, 2015-07-08 17:00:25
Pode fazer algo assim para ler os nós.

Também pode encontrar alguma explicação nesta página http://www.compoc.com/tuts/

<script type="text/javascript">
        var markers = null;
        $(document).ready(function () {
            $.get("File.xml", {}, function (xml){
              $('marker',xml).each(function(i){
                 markers = $(this);
              });
            });
        });
</script>
 2
Author: luis_laurent, 2012-10-25 22:16:26