Os dados armazenados em arquivos XML pode ser editado a partir de um navegador de Internet.
Abrir, editar e salvar XML
Agora, vamos mostrar como abrir, editar e salvar um arquivo XML que é armazenado no servidor.
Nós vamos usar XSL para transformar o documento XML em um formulário HTML. Os valores dos elementos XML será gravado em campos de entrada HTML em um formulário HTML. O formulário HTML é editável. Depois de editar os dados, os dados vai ser enviado de volta para o servidor e o arquivo XML será atualizado (we will show code for both PHP and ASP) .
O arquivo XML e o arquivo XSL
Primeiro, dê uma olhada no 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>
Então, dê uma olhada na folha seguinte 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>
O arquivo XSL acima percorre os elementos do arquivo XML e cria um campo de entrada para cada XML "field" elemento. O valor do XML "field" do elemento "id" atributo é adicionado a ambos o "id" e "name" atributos de cada campo de entrada HTML. O valor de cada XML "value" elemento é adicionado ao "value" atributo de cada campo de entrada HTML. O resultado é um formulário HTML editável que contém os valores a partir do arquivo XML.
Então, temos uma segunda folha de estilo: "tool_updated.xsl" . Este é o arquivo XSL que será usado para exibir os dados XML atualizados. Esta folha de estilos não irá resultar em um formulário HTML editável, mas uma tabela 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>
O arquivo ASP
O formulário HTML na "tool.xsl" arquivo acima tem um atributo action com um valor de "edittool.asp" .
O "edittool.asp" página contém duas funções: Os loadFile() função carrega e transforma o arquivo XML para exibição e o updateFile() função aplica as alterações no arquivo 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
%>
Tip: Se você não sabe como escrever ASP, por favor estudar nosso tutorial ASP .
O arquivo PHP
No "tool.xsl" arquivo acima, alterar o atributo action do formulário HTML para "edittool.php" .
O "edittool.php" página contém duas funções: Os loadFile() função carrega e transforma o arquivo XML para exibição e o updateFile() função aplica as alterações no arquivo 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");
}
?>
Dica: Se você não sabe como escrever PHP, por favor estudar nosso tutorial PHP .
Note: Estamos fazendo a transformação e aplicar as alterações no arquivo XML no servidor. Esta é uma solução cross-browser. O cliente só vai ficar HTML de volta do servidor - que funcionará em qualquer navegador.