Bancos de dados XML
Este tópico avançado demonstra como criar dois tipos de bancos de dados XML muito simples.
Reading XML é direta. No entanto, é impossível salvar o XML diretamente em HTML ou Hippani Animator devido a restrições de segurança. Uma página de servidor é necessário para interagir com o servidor web. Já usamos páginas de servidor ASPX escritas em c#. Outras páginas de servidor e línguas poderiam ser usadas em vez disso. ASPX e c# estão além do escopo desta documentação. Para personalizar e expandir esses exemplos, leitura adicional pode ser necessária.
Você precisará de um servidor de web do Microsoft Windows (IIS) para hospedar os arquivos ASPX. Você também precisará definir permissões de servidor da web para criar e gravar arquivos.
Bancos de dados de registros único
Este simples banco de dados armazena uma lista de valores. Cada valor tem um nome.
Por exemplo:
HighScore=10000
PlayerName=Zara
Location=France
Criar um arquivo ASPX em seu servidor web chamado XMLDatabase.aspx. Use o código a seguir. Um arquivo ASPX é simplesmente um arquivo de texto com a extensão .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());
%>
A página ASPX servidor lida com a manipulação de um arquivo XML.
Se existir o arquivo XML, em seguida, o ASPX carrega dados XML em um dicionário. Em seguida, ele verifica para ver se quaisquer novos valores foram recebidos. Se houver um novo valor, adicioná-la ao dicionário, atualizar o valor atual se ele já existir. Em seguida, cria um novo arquivo XML baseado no dicionário. Se houvesse um novo valor acrescentado, em seguida, o novo arquivo XML é salvo. Finalmente, o XML é retornado.
Você pode testar a página abrindo-o em qualquer navegador da web.
Dados são enviados por carregar a página ASPX e incluindo um nome e valor.
Por exemplo:
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
Os dados serão armazenar em um arquivo XML parecido com este:
<Data>
<HighScore>10000</HighScore>
<PlayerName>Zara</PlayerName>
<Location>France</Location>
</Data>
Este é um exemplo de como enviar dados para a página ASPX em 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);
}
}
Dados são recebidos por simplesmente carregar o arquivo ASPX.
Por exemplo:
http://www.MyWebServer.com/XMLDatabase.aspx
Este é um exemplo de como obter dados a partir da página ASPX em 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!!!");
}
}
Vários bancos de dados de registros
Este banco de dados mais complexo armazena uma lista de registros. Cada registro contém uma lista de valores. Cada valor tem um nome.
Por exemplo:
Disco 1:
FirstName=Andrew
Age=23
Disco 2:
FirstName=Andrea
Age=42
Este tipo de banco de dados XML trabalhará eficazmente para até 100 registros. Bancos de dados maiores também precisaria de vários arquivos XML ou ser conectados a um banco de dados adequado como SQL.
Criar outro arquivo ASPX no seu servidor web chamado XMLDatabase2.aspx. Use o código a seguir.
<%@ 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 de servidor ASPX é mais complexa. Novamente, ele lida com a manipulação de um arquivo XML.
Se existir o arquivo XML, em seguida, o ASPX carrega dados XML em um dicionário. Em seguida, ele verifica para ver se quaisquer novos valores foram recebidos. Se houver um índice e um novo valor, adicioná-lo para o registro no dicionário, atualizar o valor atual se ele já existir. Em seguida, cria um novo arquivo XML baseado no dicionário. Se houvesse um novo valor acrescentado, em seguida, o novo arquivo XML é salvo. Finalmente, o XML é retornado.
Você pode testar a página abrindo-o em qualquer navegador da web.
Dados são enviados por carregar a página ASPX e incluindo um índice, nome e valor.
Por exemplo:
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
Os dados serão armazenar em um arquivo XML parecido com este:
<Data>
<Record Index="1">
<FirstName>Andrew</FirstName>
<Age>23</Age>
</Record>
<Record Index="2">
<FirstName>Andrea</FirstName>
<Age>42</Age>
</Record>
</Data>
Este é um exemplo de como enviar dados para a página ASPX em 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);
}
}
Dados são recebidos por simplesmente carregar o arquivo ASPX.
Por exemplo:
http://www.MyWebServer.com/XMLDatabase.aspx
Este é um exemplo de como obter dados a partir da página ASPX em 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 documentação foi traduzida do inglês, usando um tradutor online. Pedimos desculpas se você encontrar quaisquer erros. Se você gostaria de nos ajudar a fazer as correções. Há um editor de tradução em Hippani Animator (no menu ajuda). Damos as chaves de licença livre para qualquer um que corrige mais de 100 frases. Entre em contato conosco para mais detalhes.