Bases de datos XML
Avanzado en este tema muestra cómo crear dos tipos de las bases de datos XML muy simples.
Lectura XML es hacia adelante. Sin embargo, es imposible guardar XML directamente desde HTML o Hippani Animator debido a las restricciones de seguridad. Una página del servidor es necesaria para interactuar con el servidor web. Hemos utilizado las páginas ASPX server escritas en C#. Otras páginas de servidor y lenguas podrían utilizarse en su lugar. ASPX y C# son más allá del alcance de esta documentación. Para personalizar y ampliar en estos ejemplos, lectura adicional puede ser necesaria.
Necesitará un servidor web de Microsoft Windows Server (IIS) para alojar los archivos ASPX. También necesitará establecer los permisos del servidor web para crear y escribir archivos.
Bases de datos de registros único
Esta base de datos simple almacena una lista de valores. Cada valor tiene un nombre.
Por ejemplo:
HighScore=10000
PlayerName=Zara
Location=France
Crear un archivo ASPX en su servidor web llamado XMLDatabase.aspx. Utilice el siguiente código. Un archivo ASPX es simplemente un archivo de texto con la extensión .aspx.
<%@ Page Language="C#" %>
<%@ Import namespace="System.IO" %>
<%@ Import namespace="System.Xml" %>
<%@ Import namespace="System.Collections.Generic" %>
<%
string DataFilename=Server.MapPath("Data.xml");
Dictionary<string,string> MyData=new Dictionary<string,string>();
bool DataChanged=false;
// Load the xml data into a dictionary
if(File.Exists(DataFilename)){
XmlDocument Doc=new XmlDocument();
Doc.Load(DataFilename);
XmlNode N=Doc.DocumentElement.FirstChild;
while(N!=null){ //Iterate through the nodes
if(!MyData.ContainsKey(N.Name)){ //If the dictionary does not contain the node name, add it and the text it contains.
MyData.Add(N.Name,N.InnerText);
}
N=N.NextSibling;
}
}
//Add any new Name and Value values sent to the page.
string Name=Context.Request["Name"];
string Value=Context.Request["Value"];
if(!String.IsNullOrEmpty(Name)){
if(!MyData.ContainsKey(Name)){ //If the dictionary does not contain the name, add it and the value.
MyData.Add(Name,Value);
}else{ //Replace the value if the name already exists in the dictionary.
MyData[Name]=Value;
}
DataChanged=true;
}
//Generate a new xml file.
StringBuilder NewXML=new StringBuilder();
NewXML.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n");
NewXML.Append("<Data>\r\n");
Dictionary<string,string>.Enumerator Enum=MyData.GetEnumerator();
while(Enum.MoveNext()){
NewXML.Append("<"+Enum.Current.Key+">"+HttpUtility.HtmlEncode(Enum.Current.Value)+"</"+Enum.Current.Key+">\r\n");
}
NewXML.Append("</Data>\r\n");
//Save the data file if it has been changed.
if(DataChanged){
StreamWriter SW = new StreamWriter(DataFilename);
SW.WriteLine(NewXML.ToString());
SW.Close();
}
//Return the xml file.
Context.Response.ContentType = "text/xml";
Response.Write(NewXML.ToString());
%>
La página ASPX de server encarga de la manipulación de un archivo XML.
Si existe el archivo XML, el ASPX carga los datos XML en un diccionario. Luego se comprueba si se han recibido nuevos valores. Si hay un nuevo valor, agregarla al diccionario, actualizar el valor actual si ya existe. A continuación, crea un nuevo archivo XML basado en el diccionario. Si hay un nuevo valor añadido, se guarda el nuevo archivo XML. Por último, se devuelve el XML.
Usted puede probar la página abriéndolo en cualquier navegador web.
Datos se envían por cargar la página ASPX y con un nombre y valor.
Por ejemplo:
http://www.MyWebServer.com/XMLDatabase.aspx?Name=HighScore&Value=10000
http://www.MyWebServer.com/XMLDatabase.aspx?Name=PlayerName&Value=Zara
http://www.MyWebServer.com/XMLDatabase.aspx?Name=Location&Value=France
Los datos serán tienda en un archivo XML que se parece a esto:
<Data>
<HighScore>10000</HighScore>
<PlayerName>Zara</PlayerName>
<Location>France</Location>
</Data>
Este es un ejemplo de cómo enviar datos a la página ASPX en Hippani Animator.
var Name="HighScore";
var Value="10000";
OpenXMLUrl("http://www.MyWebServer.com/XMLDatabase.aspx?Name="+escape(Name)+"&Value="+escape(Value),Result);
function Result(XML){
if(XML.status==200){
alert("Saved.");
}else{
alert("Error Code "+XML.status);
}
}
Los datos son recibido simplemente cargando el archivo ASPX.
Por ejemplo:
http://www.MyWebServer.com/XMLDatabase.aspx
Este es un ejemplo de cómo obtener datos de la página ASPX en Hippani Animator.
OpenXMLUrl("http://www.MyWebServer.com/XMLDatabase.aspx",Result);
function Result(XML){
if(XML.status==200){
var Node=XML.documentElement.firstChild;
var List="List:\r\n";
while(Node!=null){
List+=Node.nodeName+"="+Node.firstChild.nodeValue+"\r\n";
Node=Node.nextSibling;
}
alert(List);
}else{
alert(XML.status+" Error!!!");
}
}
Múltiples bases de datos de registros
Esta base de datos más complejo almacena una lista de registros. Cada registro contiene una lista de valores. Cada valor tiene un nombre.
Por ejemplo:
Disco 1:
FirstName=Andrew
Age=23
Disco 2:
FirstName=Andrea
Age=42
Este tipo de base de datos XML a trabajar eficazmente para hasta 100 registros. Bases de datos más grandes tampoco necesitaría varios archivos XML o conectadas a una base de datos adecuada como SQL.
Crear otro archivo ASPX en su servidor web llamado XMLDatabase2.aspx. Utilice el siguiente código.
<%@ Page Language="C#" %>
<%@ Import namespace="System.IO" %>
<%@ Import namespace="System.Xml" %>
<%@ Import namespace="System.Collections.Generic" %>
<%
string DataFilename=Server.MapPath("Data2.xml");
Dictionary<int,Dictionary<string,string>> MyData=new Dictionary<int,Dictionary<string,string>>();
bool DataChanged=false;
Dictionary<string,string> Record=null;
int Index=0;
// Load the xml data into a dictionary
if(File.Exists(DataFilename)){
XmlDocument Doc=new XmlDocument();
Doc.Load(DataFilename);
XmlNode N=Doc.DocumentElement.FirstChild,M=null;
while(N!=null){ //Iterate through the record nodes
Index=Convert.ToInt32(N.Attributes["Index"].Value); //Get the index value of the record.
Record=new Dictionary<string,string>();
M=N.FirstChild;
while(M!=null){ //Iterate through the value nodes
if(!Record.ContainsKey(M.Name)){ //If the record does not contain the node name, add it and the text it contains.
Record.Add(M.Name,M.InnerText);
}
M=M.NextSibling;
}
if(!MyData.ContainsKey(Index)){ //If the dictionary does not contain the record index, add it.
MyData.Add(Index,Record);
}
N=N.NextSibling;
}
}
//Add any new Name and Value values sent to the page. Use the Index value to locate the correct record.
string Name=Context.Request["Name"];
string Value=Context.Request["Value"];
Index=Convert.ToInt32(Context.Request["Index"]);
if(!String.IsNullOrEmpty(Name)&&Index>0){
if(MyData.ContainsKey(Index)){ //If the dictionary contains the record index.
Record=MyData[Index];
}else{ //If the dictionary does not contain the record. Create a new empty record and add it.
Record=new Dictionary<string,string>();
MyData.Add(Index,Record);
}
if(!Record.ContainsKey(Name)){ //If the record does not contain the name, add it and the value.
Record.Add(Name,Value);
}else{ //Replace the value if the name already exists in the record.
Record[Name]=Value;
}
DataChanged=true;
}
//Generate a new xml file.
StringBuilder NewXML=new StringBuilder();
NewXML.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n");
NewXML.Append("<Data>\r\n");
Dictionary<int,Dictionary<string,string>>.Enumerator Enum=MyData.GetEnumerator();
Dictionary<string,string>.Enumerator EnumRecord;
while(Enum.MoveNext()){
NewXML.Append("<Record Index=\""+Enum.Current.Key+"\">\r\n");
EnumRecord=Enum.Current.Value.GetEnumerator();
while(EnumRecord.MoveNext()){
NewXML.Append("<"+EnumRecord.Current.Key+">"+HttpUtility.HtmlEncode(EnumRecord.Current.Value)+"</"+EnumRecord.Current.Key+">\r\n");
}
NewXML.Append("</Record>\r\n");
}
NewXML.Append("</Data>\r\n");
//Save the data file if it has been changed.
if(DataChanged){
StreamWriter SW = new StreamWriter(DataFilename);
SW.WriteLine(NewXML.ToString());
SW.Close();
}
//Return the xml file.
Context.Response.ContentType = "text/xml";
Response.Write(NewXML.ToString());
%>
Esta página ASPX de servidor es más compleja. Una vez más, se maneja la manipulación de un archivo XML.
Si existe el archivo XML, el ASPX carga los datos XML en un diccionario. Luego se comprueba si se han recibido nuevos valores. Si hay un nuevo valor y un índice, agregarla a la registrada en el diccionario, actualizar el valor actual si ya existe. A continuación, crea un nuevo archivo XML basado en el diccionario. Si hay un nuevo valor añadido, se guarda el nuevo archivo XML. Por último, se devuelve el XML.
Usted puede probar la página abriéndolo en cualquier navegador web.
Datos se envían por cargar la página ASPX e incluyendo un índice, nombre y valor.
Por ejemplo:
http://www.MyWebServer.com/XMLDatabase2.aspx?Index=1&Name=FirstName&Value=Andrew
http://www.MyWebServer.com/XMLDatabase2.aspx?Index=1&Name=Age&Value=23
http://www.MyWebServer.com/XMLDatabase2.aspx?Index=2&Name=FirstName&Value=Andrea
http://www.MyWebServer.com/XMLDatabase2.aspx?Index=2&Name=Age&Value=42
Los datos serán tienda en un archivo XML que se parece a esto:
<Data>
<Record Index="1">
<FirstName>Andrew</FirstName>
<Age>23</Age>
</Record>
<Record Index="2">
<FirstName>Andrea</FirstName>
<Age>42</Age>
</Record>
</Data>
Este es un ejemplo de cómo enviar datos a la página ASPX en Hippani Animator.
var Index=1;
var Name="FirstName";
var Value="Andrew";
OpenXMLUrl("http://www.MyWebServer.com/XMLDatabase2.aspx?Index="+Index+"&Name="+escape(Name)+"&Value="+escape(Value),Result);
function Result(XML){
if(XML.status==200){
alert("Saved.");
}else{
alert("Error Code "+XML.status);
}
}
Se recibieron datos simplemente cargando el archivo ASPX.
Por ejemplo:
http://www.MyWebServer.com/XMLDatabase.aspx
Este es un ejemplo de cómo obtener datos de la página ASPX en Hippani Animator.
OpenXMLUrl("http://www.MyWebServer.com/XMLDatabase2.aspx",Result);
function Result(XML){
if(XML.status==200){
var Record=XML.documentElement.firstChild,Node=null;
var List="List:\r\n";
while(Record!=null){
List+="Record: "+Record.attributes.getNamedItem("Index").value+"\r\n";
Node=Record.firstChild;
while(Node!=null){
List+=" "+Node.nodeName+"="+Node.firstChild.nodeValue+"\r\n";
Node=Node.nextSibling;
}
Record=Record.nextSibling;
}
alert(List);
}else{
alert(XML.status+" Error!!!");
}
}
Esta documentación fue traducida del inglés, utilizando un traductor en línea. Le pedimos disculpas si encuentra algún error. Si desea que nos ayude a hacer las correcciones. Hay un editor de traducciones en Hippani Animator (en el menú Ayuda). Que damos claves de licencia gratis a cualquiera que corrige más de 100 frases. Póngase en contacto con nosotros para más detalles.