Heim  >  Artikel  >  Backend-Entwicklung  >  Fügen Sie neue „Datensätze“ zum XML-Dokument hinzu

Fügen Sie neue „Datensätze“ zum XML-Dokument hinzu

黄舟
黄舟Original
2017-02-11 15:54:381418Durchsuche

Das in diesem Artikel gegebene Beispiel ähnelt dem Speichern von Daten im HTML-Format in XML. Früher haben wir beim Absenden des Formulars normalerweise ein neues Dokument erstellt. Solange das Dokument bereits vorhanden ist, kann es direkt hinzugefügt werden. Die Verwendung dieser Technik ähnelt der Erstellung grundlegender Daten.

Im vorherigen Artikel habe ich gezeigt, wie XMLDOM verwendet wird. Wir können also direkt zum Beispiel dieses Artikels springen.

Das erste, was wir berücksichtigen müssen, ist das HTML-Formular, das wir zum Hinzufügen eines neuen „Datensatzes“ verwenden werden. Im Beispiel „HTML-Formulardaten in XML speichern“ haben wir dieses Formular bereits verwendet, nur den Dateinamen geändert, aber der Code ist derselbe.

AddContact.html:

<html> 
  <head> 
   <title> Contact Information </title> 
  </head> 
  <body> 
   <form action="processAdd.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>


Wir haben dieses HTML-Formular für die Verarbeitung von ADD eingerichtet. ASP. Die ASP-Seite hat hier die Funktion zu erkennen, ob XML-Dateien und ROLODEX.XML vorhanden sind. Wenn sie vorhanden sind, hängt ASP neue Einträge an die Dateien an oder erstellt sie, wenn sie nicht vorhanden sind.

Prozess Add.asp:

<% 
   &#39;-------------------------------------------------------------------- 
   &#39;The "addNewContacttoXML" Function accepts two parameters. 
   &#39;strXMLFilePath - The physical path where the XML file will be saved. 
   &#39;strFileName - The name of the XML file that will be saved. 
   &#39;-------------------------------------------------------------------- 
   Function addNewContacttoXML(strXMLFilePath, strFileName)  
    &#39;Declare local variables.  
    Dim objDom  
    Dim objRoot  
    Dim objRecord  
    Dim objField 
    Dim objFieldValue  
    Dim objattID  
    Dim objattTabOrder  
    Dim objPI  
    Dim blnFileExists  
    Dim x  
    &#39;Instantiate the Microsoft XMLDOM.  
    Set objDom = server.CreateObject("Microsoft.XMLDOM")  
    objDom.preserveWhiteSpace = True 
    &#39;Call the Load Method of the XMLDOM Object. The Load ethod has a  
    &#39;boolean return value indicating whether or not the file could be  
    &#39;loaded. If the file exists and loads it will return true, otherwise, 
    &#39;it will return false. 
    blnFileExists = objDom.Load(strXMLFilePath & "\" & strFileName)  
    &#39;Test to see if the file loaded successfully.  
    If blnFileExists = True Then  
     &#39;If the file loaded set the objRoot Object equal to the root element  
     &#39;of the XML document.  
     Set objRoot = objDom.documentElement Else  
     &#39;Create your root element and append it to the XML document.  
     Set objRoot = objDom.createElement("rolodex")  
     objDom.appendChild objRoot 
    End If  
     &#39;Create the new container element for the new record.  
     Set objRecord = objDom.createElement("contact")  
     objRoot.appendChild objRecord  
     &#39;Iterate through the Form Collection of the Request Object. 
     For x = 1 To Request.Form.Count  
      &#39;Check to see if "btn" is in the name of the form element. If it is,  
      &#39;then it is a button and we do not want to add it to the XML  
      &#39;document".  
      If instr(1,Request.Form.Key(x),"btn") = 0 Then  
       &#39;Create an element, "field".  
       Set objField = objDom.createElement("field")  
       &#39;Create an attribute, "id".  
       Set objattID = objDom.createAttribute("id")  
       &#39;Set the value of the id attribute equal the the name of the current  
       &#39;form field.  
       objattID.Text = Request.Form.Key(x)  
       &#39;The setAttributeNode method will append the id attribute to the  
       &#39;field element. objField.setAttributeNode objattID  
       &#39;Create another attribute, "taborder". This just orders the  
       &#39;elements.  
       Set objattTabOrder = objDom.createAttribute("taborder")  
        
       &#39;Set the value of the taborder attribute.  
       objattTabOrder.Text = x  
       &#39;Append the taborder attribute to the field element.  
       &#39;objField.setAttributeNode objattTabOrder  
       &#39;Create a new element, "field_value". 
       Set objFieldValue = objDom.createElement("field_value")  
       &#39;Set the value of the field_value element equal to the value of the  
       &#39;current field in the Form Collection.  
       objFieldValue.Text = Request.Form(x)  
       &#39;Append the field element as a child of the new record container  
       &#39;element, contact. objRecord.appendChild objField  
       &#39;Append the field_value element as a child of the field element. 
       objField.appendChild objFieldValue  
      End If  
     Next  
     &#39;Check once again to see if the file loaded successfully. If it did  
     &#39;not, that means we are creating a new document and need to be sure to  
     &#39;insert the XML processing instruction.  
     If blnFileExists = False then  
      &#39;Create the xml processing instruction.  
      Set objPI = objDom.createProcessingInstruction("xml", "version=&#39;1.0&#39;")  
      &#39;Append the processing instruction to the XML document.  
      objDom.insertBefore objPI, objDom.childNodes(0)  
     End If  
     &#39;Save the XML document. 
     objDom.save strXMLFilePath & "\" & strFileName  
     &#39;Release all of your object references.  
     Set objDom = Nothing  
     Set objRoot = Nothing  
     Set objRecord = Nothing  
     Set objField = Nothing  
     Set objFieldValue = Nothing  
     Set objattID = Nothing  
     Set objattTabOrder = Nothing  
     Set objPI = NothingEnd  
    Function 
    &#39;Do not break on an error. 
    On Error Resume Next 
    &#39;Call the addNewContacttoXML function, passing in the physical path to 
    &#39;save the file to and the name that you wish to use for the file. 
    addNewContacttoXML "c:","rolodex.xml" 
    &#39;Test to see if an error occurred, if so, let the user know. 
    &#39;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 
   %>


Wenn Sie den Artikel über „Speichern von HTML-Formulardaten im XML-Format“ gelesen haben, werden Sie feststellen, dass der Code zum Erweitern von Daten in eine XML-Datei ist im Grunde dasselbe wie der Code zum Erweitern von HTML-Daten in ein neues Dokument. Hier gibt es jedoch zwei Hauptunterschiede:

 &#39;Call the Load Method of the XMLDOM Object. The Load Method has a  
   &#39;boolean return value indicating whether or not the file could be  
   &#39;loaded. If the file exists and loads it will return true, otherwise,  
   &#39;it will return false.  
   blnFileExists = objDom.Load(strXMLFilePath & "\" & strFileName)  
    
   &#39;Test to see if the file loaded successfully.  
   If blnFileExists = True Then  
    &#39;If the file loaded set the objRoot Object equal to the root element  
    &#39;of the XML document.  
    Set objRoot = objDom.documentElement 
   Else  
    &#39;Create your root element and append it to the XML document.  
    Set objRoot = objDom.createElement("contact")  
    objDom.appendChild objRoot  
   End If

Der Code in diesem Abschnitt stammt aus der Funktion addNewContacttoXML. Da wir nicht jedes Mal eine neue Datei erstellen können, speichern wir stattdessen CONTACT. Wenn wir die Datei laden können, erhalten wir das Stammelement des XML-Dokuments. Wenn nicht, gehen wir davon aus, dass es nicht existiert, erstellen ein neues Element und hängen es an das XML-Dokument an.

Ein weiterer Hauptunterschied besteht darin: Wenn wir eine sekundäre Prüfung der Datei durchführen, um zu sehen, ob der LOAD erfolgreich war, können wir entscheiden, ob wir eine Verarbeitungsanweisung hinzufügen müssen. Wenn die Datei vorhanden ist, müssen wir diese Anweisung nicht hinzufügen. Wird jedoch eine neue Datei erstellt, muss diese Verarbeitungsanweisung hinzugefügt werden.


&#39;Check once again to see if the file loaded successfully. If it did  
  &#39;not, that means we are creating a new document and need to be sure to  
  &#39;insert the XML processing instruction.  
  If blnFileExists = False then  
   &#39;Create the xml processing instruction.  
   Set objPI = objDom.createProcessingInstruction("xml", "version=&#39;1.0&#39;")  
   &#39;Append the processing instruction to the XML document.  
   objDom.insertBefore objPI, objDom.childNodes(0)  
  End If

Zusätzlich zu den beiden oben genannten Unterschieden können Sie feststellen, dass der Code zum Speichern von Daten in einer neuen Datei tatsächlich derselbe ist wie der Code zum Anhängen neuer Datensätze zu vorhandenen Dateien. Wir erstellen ein neues Element, kontaktieren Sie CONTAINER, um jeden neu hinzugefügten RECORD aufzunehmen. Der Code wird in der Formularsammlung des Anforderungsobjekts iteriert, um die entsprechenden XML-Knoten zu erstellen und die Knotenwerte so festzulegen, dass sie mit denen des aktuellen Formularfelds übereinstimmen.

Das Obige ist der Inhalt des Hinzufügens neuer „Datensätze“ zum XML-Dokument. Weitere verwandte Inhalte finden Sie auf der chinesischen PHP-Website (www.php.cn)!


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn