Pregunta

Tengo el siguiente XML-

<rows>
   <row id="5">
      <cell>Item1</cell>
   <attrs>
    <attr>
      <id>1</id>
      <type>CheckBox</type>
      <values>
        <value>
          <id>10</id>
        </value>
        <value>
          <id>11</id>
        </value>
      </values>
    </attr>
     <attr>
       <id>2</id>
       <type>CheckBox</type>
       <values>
         <value>
           <id>20</id>
         </value>
         <value>
           <id>21</id>
         </value>
       </values>
     </attr>
  </attrs>
   </row>
</rows>

Lo que quiero hacer es hacer un bucle de cada una de una determinada fila.

Intenté hacer esto para obtener todos los identificadores de atributo pero también obtuve los identificadores de valores.

function fillForm(id){
    var theRow = $(theXmlDoc).find('row[id='+id+']').get()

    $(theRow).find("attr").each(function(i) 
    {
        alert($(this).find("id").text());
    });
}

También me gustaría señalar que el objetivo principal es repetir cada atributo y luego repetir cada valor mientras tengo la identificación del atributo.

P.S si piensa en una forma más fácil / sencilla de hacerlo con alguna otra biblioteca, estoy abierto a sugerencias.

Gracias de antemano,

¿Fue útil?

Solución

No tengo claro qué es lo que estás tratando de repetir, creo que una de las etiquetas en tu pregunta fue ilegible. Usted dice: "Lo que quiero hacer es hacer un bucle de cada una de una determinada fila". y creo que tenías una etiqueta allí.

De todos modos, aquí hay algunos ejemplos de extracción de datos del documento xml analizado usando jQuery. Los comentarios muestran lo que se alertará.

Creo que parte del problema es que tienes los valores de identificación como hermanos en lugar de hijos para los atributos. Parece que una estructura más coherente podría ser:

<rows>
    <row id="5">
        <cell>Item1</cell>
        <attrs>
            <attr id="1">
                <type>CheckBox</type>
                <values>
                    <value>
                        <id>10</id>
                    </value>
                    <value>
                        <id>11</id>
                    </value>
                </values>
            </attr>
            <attr id="2">
                <type>CheckBox</type>
                <values>
                    <value>
                        <id>20</id>
                    </value>
                    <value>
                        <id>21</id>
                    </value>
                </values>
            </attr>
        </attrs>
    </row>
</rows>

Pero si no tienes control sobre el xml, ignora esa sugerencia. :-)

Bien, aquí hay algunas muestras de recorrido para obtener varios datos:

Primero, obtengamos " Item1 "

<script type="text/javascript">
// Item1
$.get('sample.xml', null, function (data, textStatus) {
    alert( $(data).find('rows row[id=5] cell').text());
}, 'xml');
</script>

Ahora obtendremos el 1 y el 2:

<script type="text/javascript">
// 1
// 2
$.get('sample.xml', null, function (data, textStatus) {
    $(data).find('rows row[id=5] attrs attr > id').each( function(){
            alert($(this).text()); // 1, 2
    });
}, 'xml');
</script>

Y, por último, extraigamos los atributos principales y vinculemos los valores:

<script type="text/javascript">
// rows row[id=5] attrs attr > id 1 has inner ids of 10,11
// rows row[id=5] attrs attr > id 2 has inner ids of 20,21
$.get('sample.xml', null, function (data, textStatus) {

        var out = ''
        $(data).find('rows row[id=5] attrs attr > id').each( function(){
                out += 'rows row[id=5] attrs attr > id ' + $(this).text();
                var innerIds = [];
                $(this).siblings('values').find('value id').each(function(){
                    innerIds.push($(this).text())
                });
                out += ' has inner Ids of ' + innerIds.join(',') + '\n';
        });
        alert(out);
    }, 'xml');
</script>

Otros consejos

Esto debería funcionar para usted

function fillForm(id){
    var row = $(theXmlDoc).find('row#+'+ id);
    var ids = row.find( "attr > id");

    ids.each(function(i) 
    {
        alert($(this).text());
    });
}

PS. Puede usar xpath ya sea:

var ids = document.evaluate( '//rows/row[@id='+id + ']/attr/id/text( )', theXmlDoc, null, XPathResult.ANY_TYPE, null );
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top