백엔드 개발 XML/RSS 튜토리얼 XML 문서에 새 '레코드' 추가

XML 문서에 새 '레코드' 추가

Feb 11, 2017 pm 03:54 PM
records XML 문서

이 기사에 제공된 예는 HTML 형식 데이터를 XML로 저장하는 것과 유사합니다. 과거에는 양식이 제출되면 일반적으로 새 문서를 만들었습니다. 이제는 문서가 이미 존재하는 한 직접 추가할 수 있습니다. 이 기술의 사용은 기본 데이터를 생성하는 것과 유사합니다.

이전 기사에서는 XMLDOM을 사용하는 방법을 설명했습니다. 그럼 바로 이 글의 예시로 넘어가겠습니다.

가장 먼저 고려해야 할 것은 새 "레코드"를 추가하는 데 사용할 HTML 형식입니다. "HTML 양식 데이터를 XML로 저장" 예제에서는 이미 이 양식을 사용했으며 파일 이름만 변경했지만 코드는 동일합니다.

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>
로그인 후 복사


ADD를 처리하기 위해 이 HTML 양식을 설정했습니다. ASP. 여기 ASP 페이지에는 XML 파일과 ROLODEX.XML이 존재하는지 감지하는 기능이 있습니다. 파일이 있으면 ASP는 파일에 새 항목을 추가하고, 파일이 없으면 파일을 만들어야 합니다.

프로세스 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 
   %>
로그인 후 복사


"HTML 양식 데이터를 XML 형식으로 저장"에 대한 기사를 읽었다면 HTML 데이터 확장에 추가되는 것을 알 수 있습니다. XML 파일에 대한 코드는 기본적으로 HTML 데이터를 새 문서로 확장하는 코드와 동일합니다. 그러나 여기에는 두 가지 주요 차이점이 있습니다.

 &#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
로그인 후 복사

이 섹션의 코드는 addNewContacttoXML 함수에서 가져온 것입니다. 매번 새 파일을 만들 수 없기 때문에 대신 CONTACT를 저장합니다. 파일을 로드할 수 있으면 XML 문서의 루트 요소를 가져옵니다. 그렇지 않으면 해당 요소가 존재하지 않는다고 가정하고 새 요소를 만들어 XML 문서에 추가합니다.

또 다른 주요 차이점은 LOAD가 성공했는지 확인하기 위해 파일에 대한 2차 검사를 수행할 때 처리 명령을 추가해야 하는지 여부를 결정할 수 있다는 것입니다. 파일이 존재하는 경우 이 지시어를 추가할 필요가 없습니다. 단, 새로운 파일이 생성되는 경우에는 이 처리 명령을 추가해야 합니다.


&#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
로그인 후 복사

위의 두 가지 차이점 외에도 새 파일에 데이터를 저장하는 코드는 실제로 새 레코드를 추가하는 코드와 동일하다는 것을 알 수 있습니다. 기존 파일. 새로 추가된 각 RECORD를 수용하기 위해 CONTAINER라는 새 요소를 만듭니다. 코드는 요청 개체의 양식 컬렉션에서 반복되어 적절한 XML 노드를 생성하고 노드 값을 현재 양식 필드와 동일하게 설정합니다.

위는 XML 문서에 새로운 "기록"을 추가하는 내용입니다. 더 많은 관련 내용은 PHP 중국어 홈페이지(www.php.cn)를 참고해주세요!


본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

휴대폰에서 XML을 PDF로 변환 할 때 변환 속도가 빠르나요? 휴대폰에서 XML을 PDF로 변환 할 때 변환 속도가 빠르나요? Apr 02, 2025 pm 10:09 PM

모바일 XML에서 PDF의 속도는 다음 요인에 따라 다릅니다. XML 구조의 복잡성. 모바일 하드웨어 구성 변환 방법 (라이브러리, 알고리즘) 코드 품질 최적화 방법 (효율적인 라이브러리 선택, 알고리즘 최적화, 캐시 데이터 및 다중 스레딩 사용). 전반적으로 절대적인 답변은 없으며 특정 상황에 따라 최적화해야합니다.

휴대 전화에서 XML 파일을 PDF로 변환하는 방법은 무엇입니까? 휴대 전화에서 XML 파일을 PDF로 변환하는 방법은 무엇입니까? Apr 02, 2025 pm 10:12 PM

단일 애플리케이션으로 휴대 전화에서 직접 XML에서 PDF 변환을 완료하는 것은 불가능합니다. 두 단계를 통해 달성 할 수있는 클라우드 서비스를 사용해야합니다. 1. 클라우드에서 XML을 PDF로 변환하십시오. 2. 휴대 전화에서 변환 된 PDF 파일에 액세스하거나 다운로드하십시오.

휴대 전화에서 XML을 PDF로 변환하는 방법은 무엇입니까? 휴대 전화에서 XML을 PDF로 변환하는 방법은 무엇입니까? Apr 02, 2025 pm 10:18 PM

휴대 전화에서 XML을 PDF로 직접 변환하는 것은 쉽지 않지만 클라우드 서비스를 통해 달성 할 수 있습니다. 가벼운 모바일 앱을 사용하여 XML 파일을 업로드하고 생성 된 PDF를 수신하고 클라우드 API로 변환하는 것이 좋습니다. Cloud API는 Serverless Computing Services를 사용하고 올바른 플랫폼을 선택하는 것이 중요합니다. XML 구문 분석 및 PDF 생성을 처리 할 때 복잡성, 오류 처리, 보안 및 최적화 전략을 고려해야합니다. 전체 프로세스에는 프론트 엔드 앱과 백엔드 API가 함께 작동해야하며 다양한 기술에 대한 이해가 필요합니다.

Web.xml을 열는 방법 Web.xml을 열는 방법 Apr 03, 2025 am 06:51 AM

Web.xml 파일을 열려면 다음 방법을 사용할 수 있습니다. 텍스트 편집기 (예 : 메모장 또는 문자 메시지)를 사용하여 통합 개발 환경 (예 : Eclipse 또는 NetBeans)을 사용하여 명령을 편집하십시오 (Windows : Notepad Web.xml; Mac/Linux : Open -A Texted web.xml).

권장 XML 서식 도구 권장 XML 서식 도구 Apr 02, 2025 pm 09:03 PM

XML 서식 도구는 규칙에 따라 코드를 입력하여 가독성과 이해를 향상시킬 수 있습니다. 도구를 선택할 때는 사용자 정의 기능, 특수 상황 처리, 성능 및 사용 편의성에주의하십시오. 일반적으로 사용되는 도구 유형에는 온라인 도구, IDE 플러그인 및 명령 줄 도구가 포함됩니다.

XML을 PDF로 변환 할 수있는 모바일 앱이 있습니까? XML을 PDF로 변환 할 수있는 모바일 앱이 있습니까? Apr 02, 2025 pm 08:54 PM

XML을 PDF로 직접 변환하는 응용 프로그램은 근본적으로 다른 두 형식이므로 찾을 수 없습니다. XML은 데이터를 저장하는 데 사용되는 반면 PDF는 문서를 표시하는 데 사용됩니다. 변환을 완료하려면 Python 및 ReportLab과 같은 프로그래밍 언어 및 라이브러리를 사용하여 XML 데이터를 구문 분석하고 PDF 문서를 생성 할 수 있습니다.

XML 형식을 여는 방법 XML 형식을 여는 방법 Apr 02, 2025 pm 09:00 PM

대부분의 텍스트 편집기를 사용하여 XML 파일을여십시오. 보다 직관적 인 트리 디스플레이가 필요한 경우 Oxygen XML 편집기 또는 XMLSPy와 같은 XML 편집기를 사용할 수 있습니다. 프로그램에서 XML 데이터를 처리하는 경우 프로그래밍 언어 (예 : Python) 및 XML 라이브러 (예 : XML.etree.elementtree)를 사용하여 구문 분석해야합니다.

XML 온라인 서식 XML 온라인 서식 Apr 02, 2025 pm 10:06 PM

XML 온라인 형식 도구는 지저분한 XML 코드를 읽기 쉬운 형식으로 자동 구성하고 형식을 유지 관리합니다. XML의 구문 트리를 구문 분석하고 서식 규칙을 적용함으로써 이러한 도구는 코드의 구조를 최적화하여 유지 관리 가능성과 팀워크 효율성을 향상시킵니다.

See all articles