Cách tạo tệp XML từ biểu mẫu HTML bằng JavaScript

Thông thường, việc gửi biểu mẫu trong ASP được ghi vào một số loại hệ thống quản lý cơ sở dữ liệu. Tuy nhiên, nếu bạn cần dữ liệu gửi biểu mẫu của mình dễ mang theo hơn, nó có thể được ghi vào tệp XML. Điều này đặc biệt hữu ích khi dữ liệu bạn đang thu thập trên trang Web của mình sẽ được gửi đến các ứng dụng trên nền tảng không phải Windows. Vì XML hoàn toàn di động trên tất cả các nền tảng nên dữ liệu sẽ không cần phải chuyển đổi

Để viết một biểu mẫu gửi tới một tài liệu XML, cần phải tạo một tài liệu XML mới bằng cách sử dụng Đối tượng Microsoft XMLDOM. Đối tượng XMLDOM có một thư viện đối tượng mở rộng có thể được sử dụng để tạo các phần tử, thuộc tính và giá trị sẽ tạo nên tài liệu XML. Tôi sẽ không đề cập đến toàn bộ mô hình đối tượng, bởi vì nó rất rộng và có thể chiếm toàn bộ một phần của trang Web này.

Sau khi Đối tượng XMLDOM đã được khởi tạo, cấu trúc của XML phải được trình bày bằng cách tạo các tham chiếu đối tượng tới các thành phần tạo nên mỗi lớp của tài liệu XML. Sau đây là một ví dụ về cách XMLDOM sẽ được khởi tạo và tham chiếu đến phần tử gốc được tạo. Sau khi phần tử gốc được tạo, nó được thêm vào Tài liệu XMLDOM. Sau đó, các phần tử con được tạo và nối vào phần tử gốc và sau đó tài liệu được lưu

Khởi tạo đối tượng Microsoft XMLDOM

<%
 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 "MyXMLDoc.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:\MyXMLDoc.xml"
%>

Khi tài liệu đã được lưu, nếu bạn mở tài liệu, nó sẽ giống như danh sách mã sau

MyXMLDoc. xml

<?xml version="1.0"?>
<rootElement>
 <childElement1 />
 <childElement2 />
</rootElement>

Trong “MyXMLDoc. xml”, các phần tử childElement1 và childElement2 được hiển thị dưới dạng các phần tử trống. Nếu chúng chứa các giá trị, mỗi giá trị sẽ được hiển thị với các thẻ mở và đóng kèm theo giá trị của phần tử

Bây giờ, hãy xem xét ý tưởng viết một biểu mẫu HTML gửi tới một tài liệu XML. Ở trên chúng ta đã thấy cách chúng ta có thể tạo và lưu một tài liệu XML. Việc viết biểu mẫu gửi tới tài liệu XML chỉ trở thành vấn đề lặp qua Bộ sưu tập Biểu mẫu của Đối tượng Yêu cầu và ghi giá trị của từng trường biểu mẫu vào một giá trị phần tử XML. Điều này có thể được thực hiện với Active Server Pages

Thí dụ. Gửi biểu mẫu gửi tới XML

Dưới đây là một biểu mẫu HTML bình thường mà chúng tôi sẽ sử dụng cho ví dụ này. Biểu mẫu này yêu cầu tên, địa chỉ, số điện thoại và địa chỉ email của người dùng. Thông tin này sẽ được ghi vào một tệp XML để lưu trữ

NhậpLiên hệ. html

<html>
<head>
 <title>
  Contact Information
 </title>
</head>
<body>
 <form action="processForm.asp" method="post">
  <h3>Enter your contact information</h3>
  First Name: <input type="text" id="firstName" name="firstName"><br>
  Last Name: <input type="text" id="lastName" name="lastName"><br>
  Address #1: <input type="text" id="address1" name="address1"><br>
  Address #2: <input type="text" id="address2" name="address2"><br>
  Phone Number: <input type="text" id="phone" name="phone"><br>
  E-Mail: <input type="text" id="email" name="email"><br>
  <input type="submit" id="btnSub" name="btnSub" value="Submit"><br>
 </form>
</body>
</html>

Hành động cho biểu mẫu HTML này được đặt thành processForm. asp. Đây là một trang ASP sẽ gọi một hàm lặp qua các trường biểu mẫu và ghi các giá trị của chúng vào một tệp XML

quy trìnhForm. asp

<%

'--------------------------------------------------------------------
'The "ConvertFormtoXML" Function accepts to parameters.
'strXMLFilePath - The physical path where the XML file will be saved.
'strFileName - The name of the XML file that will be saved.
'--------------------------------------------------------------------

Function ConvertFormtoXML(strXMLFilePath, strFileName)

 'Declare local variables.
 Dim objDom
 Dim objRoot
 Dim objField
 Dim objFieldValue
 Dim objattID
 Dim objattTabOrder
 Dim objPI
 Dim x


 'Instantiate the Microsoft XMLDOM.
 Set objDom = server.CreateObject("Microsoft.XMLDOM")
 objDom.preserveWhiteSpace = True


 'Create your root element and append it to the XML document.
 Set objRoot = objDom.createElement("contact")
 objDom.appendChild objRoot


 'Iterate through the Form Collection of the Request Object.
 For x = 1 To Request.Form.Count

  'Check to see if "btn" is in the name of the form element.
  'If it is, then it is a button and we do not want to add it
  'to the XML document.
  If instr(1,Request.Form.Key(x),"btn") = 0 Then

   'Create an element, "field".
   Set objField = objDom.createElement("field")

   'Create an attribute, "id".
   Set objattID = objDom.createAttribute("id")

   'Set the value of the id attribute equal the the name of
   'the current form field.
   objattID.Text = Request.Form.Key(x)

   'The setAttributeNode method will append the id attribute
   'to the field element.
   objField.setAttributeNode objattID

   'Create another attribute, "taborder". This just orders the
   'elements.
   Set objattTabOrder = objDom.createAttribute("taborder")

   'Set the value of the taborder attribute.
   objattTabOrder.Text = x

   'Append the taborder attribute to the field element.
   objField.setAttributeNode objattTabOrder

   'Create a new element, "field_value".
   Set objFieldValue = objDom.createElement("field_value")

   'Set the value of the field_value element equal to
   'the value of the current field in the Form Collection.
   objFieldValue.Text = Request.Form(x)

   'Append the field element as a child of the root element.
   objRoot.appendChild objField

   'Append the field_value element as a child of the field elemnt.
   objField.appendChild objFieldValue
  End If
 Next 


 'Create the xml processing instruction.
 Set objPI = objDom.createProcessingInstruction("xml", "version='1.0'")

 'Append the processing instruction to the XML document.
 objDom.insertBefore objPI, objDom.childNodes(0)


 'Save the XML document.
 objDom.save strXMLFilePath & "\" & strFileName


 'Release all of your object references.
 Set objDom = Nothing
 Set objRoot = Nothing
 Set objField = Nothing
 Set objFieldValue = Nothing
 Set objattID = Nothing
 Set objattTabOrder = Nothing
 Set objPI = Nothing
End Function


'Do not break on an error.
On Error Resume Next


'Call the ConvertFormtoXML function, passing in the physical path to
'save the file to and the name that you wish to use for the file.
ConvertFormtoXML "c:","Contact.xml"


'Test to see if an error occurred, if so, let the user know.
'Otherwise, tell the user that the operation was successful.
If err.number <> 0 then
 Response.write("Errors occurred while saving your form submission.")
Else
 Response.write("Your form submission has been saved.")
End If
%>

Nếu bạn sử dụng mã này trong các ứng dụng của riêng mình, hãy nhớ một điều, khi Hàm “ConvertFormtoXML” chạy, nếu tên tệp XML được chỉ định đã tồn tại, nó sẽ bị ghi đè. Tôi khuyên bạn nên tạo động các tên tệp ngẫu nhiên trước khi gọi Hàm “ConvertFormtoXML”. Bằng cách đó, bạn sẽ không bao giờ có nguy cơ ghi đè lên bất kỳ dữ liệu có giá trị nào

Tệp XML được tạo bởi ví dụ này sẽ xuất hiện (tương tự như) như sau

Tiếp xúc. xml

<?xml version="1.0" ?>
<contact>
 <field id="firstName" taborder="1">
  <field_value>Michael</field_value> 
 </field>
 <field id="lastName" taborder="2">
  <field_value>Qualls</field_value> 
 </field>
 <field id="address1" taborder="3">
  <field_value>2129 NW 27th St.</field_value> 
 </field>
 <field id="address2" taborder="4">
  <field_value /> 
 </field>
 <field id="phone" taborder="5">
  <field_value>4055253988</field_value> 
 </field>
 <field id="email" taborder="6">
  <field_value>[email protected]</field_value> 
 </field>
</contact>

Tôi khuyên bạn nên sao chép mã cho EnterContact. htm và processForm. asp tới các trang cùng tên trên máy chủ Web của bạn và chạy ví dụ. Đảm bảo rằng bạn sử dụng đường dẫn và tên tệp phù hợp với máy chủ của mình. Kiểm tra tệp XML khi bạn hoàn tất

Làm cách nào để chuyển đổi biểu mẫu HTML sang XML?

Cách chuyển đổi HTML sang XML .
Khởi tạo một Tài liệu mới
Tài liệu cuộc gọi. Phương thức xử lý với chỉ mục trang và đường dẫn tệp đầu ra làm tham số
Lưu tệp XML đầu ra

Tôi làm cách nào để lấy dữ liệu biểu mẫu bằng JavaScript?

Phương thức serializeArray() tạo một mảng đối tượng (tên và giá trị) bằng cách tuần tự hóa các giá trị biểu mẫu . Phương pháp này có thể được sử dụng để lấy dữ liệu biểu mẫu.

Chúng ta có thể sử dụng XML trong JavaScript không?

Với một vài dòng mã JavaScript, bạn có thể đọc tệp XML và cập nhật nội dung dữ liệu của bất kỳ trang HTML nào .