HTML Tutorials |
|
XML Tutorials |
|
Browser Scripting |
|
Server Scripting |
|
.NET (dotnet) |
|
Multimedia |
|
Web Building |
|
Java Tutorials |
|
Programming Langauges |
|
Soft Skills |
|
Database Tutorials |
|
Operating System |
|
Software Testing |
|
SAP Module |
|
Networking Programming |
|
Microsoft Office |
|
Accounting |
|
|
|
|
Para submeter dados em XML
|
As submissões do formulário no ASP são escritas a alguma sorte do sistema de gerência da base de dados. Entretanto, se você quiser seus dados da submissão do formulário ser mais portáteis, pode-se escrever a uma lima de XML. Isto é especialmente útil quando os dados que você está recolhendo em seu Web site serão emitidos às aplicações em plataformas de non-Windows. Desde que os dados de XML não necessitam convertido, são completamente portáteis através de todas as plataformas. A fim escrever uma submissão do formulário a um original de XML, é necessário criar um original novo de XML usando o objeto de Microsoft XMLDOM. O objeto de XMLDOM tem uma biblioteca de objeto extensiva que possa ser usada criar os atributos, os elementos, e os valores que comporã0 o original de XML. Aqui nós não somos tampa o modelo inteiro do objeto, porque é muito extensivo e poderia compor uma seção inteira deste Web site por se. Depois que o objeto de XMLDOM foi instantiated, a estrutura do XML deve ser colocado para fora criando referências do objeto aos elementos que compõem cada camada do original de XML. O seguinte é um exemplo de como o XMLDOM seria instantiated e uma referência ao elemento da raiz criado. Depois que o elemento da raiz é criado, está adicionado ao original de XMLDOM. Os elementos da criança são criados então e adicionado ao elemento da raiz e o original é conservado então.
|
Criando e conservando uma lima de XML
|
Se os dados deverem ser emitida às aplicações em plataformas de non-Windows armazenar dados em limas de XML é útil. Recordar que os dados não necessitarão ser convertidos porque XML é portátil através de todas as plataformas
Agora nós aprendemos como criar e conservar uma lima de XML. A lima de XML abaixo será nomeada “Mydoc.xml” e armazenada no diretório de c no usuário. Nós usaremos o objeto do ASP e do XMLDOM de Microsoft criar e conservar a lima de XML:
|
<%
Dim objDom
Dim objRoot
Dim objChild1
Dim objChild2
Dim objPI
'Instantiate the XMLDOM object using the CreateObject Method of the
'Server Object.
Set objDom = Server.CreateObject("Microsoft.XMLDOM")
'Create a reference to an IXMLDOMElement (XML Element) Object by
'calling the createElement Method of the XMLDOM. The createElement
'Method accepts one paramter, a string representing the name of the
'element. The return value is passed to the objRoot variable. This
'element reference will represent the root element of the XML
'Document.
Set objRoot = objDom.createElement("rootElement")
'Use the appendChild Method of the XMLDOM Object to add the objRoot
'Element Reference to the XML Document.
objDom.appendChild objRoot
'Now, following the same steps, you will create references to the
'child elements for the XML Document. The only difference is, when the
'child elements are appended to the document, you will call the
'appendChild Method of the IXMLDOMElement Object rather than the
'appendChild Method of the XMLDOM Object. By using the IXMLDOMElement
'to append the children, you are differentiating (and applying tiered
'structure to) the child elements from the root element.
Set objChild1 = objDom.createElement("childElement1")
objRoot.appendChild objChild1
Set objChild2 = objDom.createElement("childElement2")
objRoot.appendChild objChild2
'The final step to take care of before saving this document is to add
'an XML processing instruction. This is necessary so that XML parsers
'will recognize this document as an XML document.
Set objPI = objDom.createProcessingInstruction("xml","version='1.0'")
'Call the insertBefore Method of the XMLDOM Object in order to insert
'the processing instruction before the root element (the zero element
'in the XMLDOM childNodes Collection).
objDom.insertBefore objPI, objDom.childNodes(0)
'Calling the Save Method of the XMLDOM Object will save this XML
'document to your disk drive. In this case, the document will be saved
'to the "c:" drive and will be named "Mydoc.xml". When saving an
'XML document, if the file does not exist, it will be created. If it
'does exist, it will be overwritten.
objDom.Save "c:\Mydoc.xml"
%>
|
Após excepto seu original se você abrir o original olhará como a seguinte lista de códigos.
|
<?xml version="1.0"?>
<rootElement>
<childElement1 />
<childElement2 />
</rootElement>
|
Exemplo do formulário real
|
Deixar-nos que nós olhamos um exemplo real do formulário do HTML.
O formulário do HTML abaixo pede o nome, país, E-mail e endereço do usuário. Esta informação será escrita então a uma lima de XML para o armazenamento.
“customers.htm”:
|
<html>
<body>
<form action="saveForm.asp" method="post">
<p><b>Enter your contact information</b></p>
First Name: <input type="text" id="fname" name="fname"><br />
Last Name: <input type="text" id="lname" name="lname"><br />
Country: <input type="text" id="country" name="country"><br />
Email: <input type="text" id="email" name="email"><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>
|
A ação para o formulário do HTML acima é ajustada a “saveForm.asp”. A lima de “saveForm.asp” é uma página do ASP que dê laços através dos campos do formulário e armazene seus valores em uma lima de XML:
|
<%
dim xmlDoc
dim rootEl,fieldName,fieldValue,attID
dim p,i
'Do not stop if an error occurs
On Error Resume Next
Set xmlDoc = server.CreateObject("Microsoft.XMLDOM")
xmlDoc.preserveWhiteSpace=true
'Create a root element and append it to the document
Set rootEl = xmlDoc.createElement("customer")
xmlDoc.appendChild rootEl
'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
'Create a field and a value element, and an id attribute
Set fieldName = xmlDoc.createElement("field")
Set fieldValue = xmlDoc.createElement("value")
Set attID = xmlDoc.createAttribute("id")
'Set the value of the id attribute equal to the name of
'the current form field
attID.Text = Request.Form.Key(i)
'Append the id attribute to the field element
fieldName.setAttributeNode attID
'Set the value of the value element equal to
'the value of the current form field
fieldValue.Text = Request.Form(i)
'Append the field element as a child of the root element
rootEl.appendChild fieldName
'Append the value element as a child of the field element
fieldName.appendChild fieldValue
end if
next
'Add an XML processing instruction
'and insert it before the root element
Set p = xmlDoc.createProcessingInstruction("xml","version='1.0'")
xmlDoc.insertBefore p,xmlDoc.childNodes(0)
'Save the XML file
xmlDoc.save "c:\Customer.xml"
'Release all object references
set xmlDoc=nothing
set rootEl=nothing
set fieldName=nothing
set fieldValue=nothing
set attID=nothing
set p=nothing
'Test to see if an error occurred
if err.number<>0 then
response.write("Error: No information saved.")
else
response.write("Your information has been saved.")
end if
%>
|
Nota: Se a lima de XML - o nome especificado já existe, ele overwritten!
A lima de XML que será produzida pelo código acima olhará qualquer outra coisa semelhante (“Customer.xml”):
|
<?xml version="1.0" ?>
<customer>
<field id="firstName">
<value>Hege</value>
</field>
<field id="lastName">
<value>Refsnes</value>
</field>
<field id="country">
<value>Norway</value>
</field>
<field id="email">
<value>mymail@myaddress.com</value>
</field>
</customer>
|
Keywords: xml document, document object model, text node, child node,save xml data, xml sample, xml to data, xml schema,xml parsing
|
|
HTML Quizes |
|
XML Quizes |
|
Browser Scripting Quizes |
|
Server Scripting Quizes |
|
.NET (dotnet) Quizes |
|
Multimedia Quizes |
|
Web Building Quizes |
|
Java Quizes |
|
Programming Langauges Quizes |
|
Soft Skills Quizes |
|
Database Quizes |
|
Operating System Quizes |
|
Software Testing Quizes |
|
SAP Module Quizes |
|
Networking Programming Quizes |
|
Microsoft Office Quizes |
|
Accounting Quizes |
|
|