XML DOM 노드 트리 탐색
탐색 (Traverse)은 노드 트리에서 반복이나 이동을 의미합니다.
예제
아래 예제는 XML 파일을 사용합니다 books.xml。
함수 loadXMLString()이는 외부 JavaScript에 위치하고 XML 파일을 로드하는 데 사용됩니다.
- 노드 트리를 탐색하다
- <book> 요소의 모든 자식 노드를 반복합니다.
노드 트리 탐색
XML 문서를 반복할 필요가 많습니다. 예를 들어: 각 요소의 값을 추출해야 할 때.
이 과정은 '노드 트리 탐색'이라고 합니다.
아래 예제는 <book>의 모든 자식 노드를 반복하고 이름 및 값을 표시합니다:
<html> <head> <script type="text/javascript" src="loadxmlstring.js"></script> </head> <body> <script type="text/javascript"> text="<book>"; text=text+"<title>Harry Potter</title>"; text=text+"<author>J K. Rowling</author>"; text=text+"<year>2005</year>"; text=text+"</book>"; xmlDoc=loadXMLString(text); // documentElement 항상 루트 노드를 대표합니다 x=xmlDoc.documentElement.childNodes; for (i=0;i<x.length;i++) { document.write(x[i].nodeName); document.write(": "); document.write(x[i].childNodes[0].nodeValue); document.write("<br />"); } </script> </body> </html>
출력:
title: Harry Potter author: J K. Rowling year: 2005
예제 설명:
- loadXMLString() XML 문자열을 xmlDoc에 로드합니다
- 루트 요소의 자식 노드를 가져옵니다
- 각 자식 노드의 이름과 텍스트 노드의 노드 값을 출력합니다