Tutorial XML

INICIO XML Introducción XML XML Cómo utilizar Árbol XML Sintaxis XML Elementos XML Atributos XML Espacios de nombres XML Pantalla XML Solicitud Http XML Analizador XML DOM XML XPath XML XML XSLT XQuery XML Enlace X XML Validador XML DTD XML Esquema XML Servidor XML Ejemplos XML Cuestionario XML Certificado XML

XML-AJAX

AJAX Introducción AJAX XMLHttp Solicitud AJAX Respuesta AJAX Archivo XML AJAX AJAXPHP Ajax ASP Base de datos AJAX Aplicaciones AJAX Ejemplos de AJAX

DOM XML

DOM Introducción Nodos DOM Acceso DOM Información del nodo DOM Lista de nodos DOM Atravesando DOM Navegación DOM DOM obtener valores Nodos de cambio de DOM Eliminar nodos DOM Nodos de reemplazo de DOM DOM Crear nodos Agregar nodos DOM Nodos de clonación de DOM Ejemplos de DOM

Tutorial XPath

Introducción a XPath Nodos XPath Sintaxis XPath Ejes XPath Operadores XPath Ejemplos de XPath

Tutorial XSLT

XSLT Introducción Idiomas XSL Transformación XSLT XSLT <plantilla> XSLT <valor-de> XSLT <para-cada> XSLT <ordenar> XSLT <si> XSLT <elegir> Aplicar XSLT XSLT en el cliente XSLT en el servidor XSLT Editar XML Ejemplos de XSLT

Tutorial de XQuery

Introducción a XQuery Ejemplo de XQuery XQuery FLWOR XQuery HTML Términos de XQuery Sintaxis XQuery XQuery Agregar Seleccionar XQuery Funciones XQuery

DTD XML

Introducción a DTD Bloques de construcción DTD Elementos DTD Atributos DTD Elementos DTD vs Attr Entidades DTD Ejemplos de DTD

Esquema XSD

XSD Introducción XSD Cómo XSD <esquema> Elementos XSD Atributos XSD Restricciones XSD

Complejo XSD

Elementos XSD XSD vacío Solo elementos XSD Solo texto XSD XSD mixto Indicadores XSD XSD <cualquiera> XSD <cualquieratributo> Sustitución XSD Ejemplo XSD

Datos XSD

Cadena XSD Fecha XSD XSD Numérico Miscelánea XSD Referencia XSD

Servicios web

Servicios XML XML WSDL JABÓN XML XML RDF RSS XML

Referencias

Tipos de nodos DOM Nodo DOM Lista de nodos DOM DOM NamedNodeMap Documento DOM Elemento DOM Atributo DOM Texto DOM DOM CDATA Comentario DOM DOM XMLHttpSolicitud Analizador DOM Elementos XSLT Funciones XSLT/XPath

XSLT - Edición de XML


Los datos almacenados en archivos XML se pueden editar desde un navegador de Internet.


Abrir, editar y guardar XML

Ahora, le mostraremos cómo abrir, editar y guardar un archivo XML que está almacenado en el servidor.

Usaremos XSL para transformar el documento XML en un formulario HTML. Los valores de los elementos XML se escribirán en campos de entrada HTML en un formulario HTML. El formulario HTML es editable. Después de editar los datos, los datos se volverán a enviar al servidor y el archivo XML se actualizará (mostraremos el código para PHP y ASP).


El archivo XML y el archivo XSL

Primero, eche un vistazo al documento XML ("tool.xml"):

<?xml version="1.0" encoding="UTF-8"?>
<tool>
  <field id="prodName">
    <value>HAMMER HG2606</value>
  </field>
  <field id="prodNo">
    <value>32456240</value>
  </field>
  <field id="price">
    <value>$30.00</value>
  </field>
</tool>

Ver el archivo XML .

Luego, eche un vistazo a la siguiente hoja de estilo ("tool.xsl"):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <html>
  <body>
  <form method="post" action="edittool.asp">
  <h2>Tool Information (edit):</h2>
  <table border="0">
    <xsl:for-each select="tool/field">
    <tr>
      <td><xsl:value-of select="@id"/></td>
      <td>
      <input type="text">
      <xsl:attribute name="id">
        <xsl:value-of select="@id" />
      </xsl:attribute>
      <xsl:attribute name="name">
        <xsl:value-of select="@id" />
      </xsl:attribute>
      <xsl:attribute name="value">
        <xsl:value-of select="value" />
      </xsl:attribute>
      </input>
      </td>
    </tr>
    </xsl:for-each>
  </table>
  <br />
  <input type="submit" id="btn_sub" name="btn_sub" value="Submit" />
  <input type="reset" id="btn_res" name="btn_res" value="Reset" />
  </form>
  </body>
  </html>
</xsl:template>

</xsl:stylesheet>

Ver el archivo XSL .

El archivo XSL anterior recorre los elementos del archivo XML y crea un campo de entrada para cada elemento de "campo" XML. El valor del atributo "id" del elemento "campo" XML se agrega a los atributos "id" y "nombre" de cada campo de entrada HTML. El valor de cada elemento "valor" XML se agrega al atributo "valor" de cada campo de entrada HTML. El resultado es un formulario HTML editable que contiene los valores del archivo XML.

Luego, tenemos una segunda hoja de estilo: "tool_updated.xsl". Este es el archivo XSL que se utilizará para mostrar los datos XML actualizados. Esta hoja de estilo no dará como resultado un formulario HTML editable, sino una tabla HTML estática:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <html>
  <body>
  <h2>Updated Tool Information:</h2>
  <table border="1">
    <xsl:for-each select="tool/field">
    <tr>
      <td><xsl:value-of select="@id" /></td>
      <td><xsl:value-of select="value" /></td>
    </tr>
    </xsl:for-each>
  </table>
  </body>
  </html>
</xsl:template>

</xsl:stylesheet>

Ver el archivo XSL .



El archivo PHP

En el archivo "tool.xsl" anterior, cambie el atributo de acción del formulario HTML a "edittool.php".

La página "edittool.php" contiene dos funciones: la función loadFile() carga y transforma el archivo XML para su visualización y la función updateFile() aplica los cambios al archivo XML:

<?php
function loadFile($xml, $xsl)
{
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);

$xslDoc = new DOMDocument();
$xslDoc->load($xsl);

$proc = new XSLTProcessor();
$proc->importStyleSheet($xslDoc);
echo $proc->transformToXML($xmlDoc);
}

function updateFile($xml)
{
$xmlLoad = simplexml_load_file($xml);
$postKeys = array_keys($_POST);

foreach($xmlLoad->children() as $x)
{
  foreach($_POST as $key=>$value)
  {
    if($key == $x->attributes())
    {
      $x->value = $value;
    }
  }
}

$xmlLoad->asXML($xml);
loadFile($xml,"tool_updated.xsl");
}

if($_POST["btn_sub"] == "")
{
  loadFile("tool.xml", "tool.xsl");
}
else
{
  updateFile("tool.xml");
}
?>

Sugerencia: si no sabe cómo escribir PHP, estudie nuestro tutorial de PHP .

Nota: Estamos haciendo la transformación y aplicando los cambios al archivo XML en el servidor. Esta es una solución de navegador cruzado. El cliente solo obtendrá HTML del servidor, lo que funcionará en cualquier navegador.


El archivo ASP

El formulario HTML en el archivo "tool.xsl" anterior tiene un atributo de acción con un valor de "edittool.asp".

La página "edittool.asp" contiene dos funciones: la función loadFile() carga y transforma el archivo XML para mostrarlo y la función updateFile() aplica los cambios al archivo XML:

<%
function loadFile(xmlfile,xslfile)
Dim xmlDoc,xslDoc
'Load XML and XSL file
set xmlDoc = Server.CreateObject("Microsoft.XMLDOM")
xmlDoc.async = false
xmlDoc.load(xmlfile)
set xslDoc = Server.CreateObject("Microsoft.XMLDOM")
xslDoc.async = false
xslDoc.load(xslfile)
'Transform file
Response.Write(xmlDoc.transformNode(xslDoc))
end function

function updateFile(xmlfile)
Dim xmlDoc,rootEl,f
Dim i
'Load XML file
set xmlDoc = Server.CreateObject("Microsoft.XMLDOM")
xmlDoc.async = false
xmlDoc.load(xmlfile)

'Set the rootEl variable equal to the root element
Set rootEl = xmlDoc.documentElement

'Loop through the form collection
for i = 1 To Request.Form.Count
  'Eliminate button elements in the form
  if instr(1,Request.Form.Key(i),"btn_")=0 then
    'The selectSingleNode method queries the XML file for a single node
    'that matches a query. This query requests the value element that is
    'the child of a field element that has an id attribute which matches
    'the current key value in the Form Collection. When there is a match -
    'set the text property equal to the value of the current field in the
    'Form Collection.
    set f = rootEl.selectSingleNode("field[@id='" & _
    Request.Form.Key(i) & "']/value")
    f.Text = Request.Form(i)
  end if
next

'Save the modified XML file
xmlDoc.save xmlfile

'Release all object references
set xmlDoc=nothing
set rootEl=nothing
set f=nothing

'Load the modified XML file with a style sheet that
'allows the client to see the edited information
loadFile xmlfile,server.MapPath("tool_updated.xsl")
end function

'If form is submitted, update the XML file and display result
' - if not, transform the XML file for editing
if Request.Form("btn_sub")="" then
  loadFile server.MapPath("tool.xml"),server.MapPath("tool.xsl")
else
  updateFile server.MapPath("tool.xml")
end if
%>