XML의 DOM - 교체 노드
replaceChild () 메서드는 지정된 노드를 대체합니다.
nodeValue를 속성은 텍스트 노드의 텍스트를 대체합니다.
시도 - 예
다음 예는 XML이 파일을 사용 Books.xml을을 .
기능 loadXMLDoc () 외부 자바 스크립트는 XML 파일을로드하는 데 사용됩니다.
요소 노드를 교체
이 예에서는 제 <책> 노드를 대체 replaceChild ()를 사용한다.
데이터 대체 텍스트 노드
이 예는 텍스트 노드 내의 데이터를 대체하는 nodeValue를 속성을 사용한다.
요소 노드를 교체
replaceChild () 메서드는 노드를 교체하는 데 사용됩니다.
다음 코드는 첫 번째 <책> 요소를 대체합니다
예
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.documentElement;
//create a book element, title element and a text node
newNode=xmlDoc.createElement("book");
newTitle=xmlDoc.createElement("title");
newText=xmlDoc.createTextNode("A Notebook");
//add the text node to the title node,
newTitle.appendChild(newText);
//add the title node to the book node
newNode.appendChild(newTitle);
y=xmlDoc.getElementsByTagName("book")[0]
//replace the first book node with the new node
x.replaceChild(newNode,y);
x=xmlDoc.documentElement;
//create a book element, title element and a text node
newNode=xmlDoc.createElement("book");
newTitle=xmlDoc.createElement("title");
newText=xmlDoc.createTextNode("A Notebook");
//add the text node to the title node,
newTitle.appendChild(newText);
//add the title node to the book node
newNode.appendChild(newTitle);
y=xmlDoc.getElementsByTagName("book")[0]
//replace the first book node with the new node
x.replaceChild(newNode,y);
»시도
예 설명 :
- 사용 loadXMLDoc을 () "에 Books.xml을 해당 xmldoc에"
- 새로운 요소 노드 <책> 작성
- 새로운 요소 노드 <제목> 작성
- 텍스트 "A 노트북"로 새로운 텍스트 노드를 만듭니다
- 새로운 요소 노드 <제목>이 새로운 텍스트 노드를 추가
- 새로운 요소 노드 <책>에 새로운 요소 노드 <제목> 추가
- 새로운 <책> 요소 노드의 첫 번째 <책> 요소 노드를 교체하려면
데이터 대체 텍스트 노드
replaceData () 메소드는 텍스트 노드 내의 데이터를 대체하기 위해 사용된다.
replaceData () 메소드는 세 개의 인수를 사용합니다 :
- 오프셋 - 어디에서 문자를 교체 시작합니다. 오프셋 값은 0으로 시작됩니다.
- 길이 - 문자 수 교체 할
- 문자열 - 삽입 할 문자열
예
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.replaceData(0,8,"Easy");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.replaceData(0,8,"Easy");
»시도
예 설명 :
- 사용 loadXMLDoc을 () "에 Books.xml을 해당 xmldoc에"
- 첫 번째 텍스트 노드를 가져옵니다 <제목> 요소 노드
- 텍스트 노드의 제 8 문자를 이용 ReplaceData 방법은 "쉬운"로 대체
대신 nodeValue를 속성을 사용하여
nodeValue를 속성 쉬울 것이다 텍스트 노드의 데이터를 교체한다.
다음 코드는 "쉬운 이탈리아어"로 텍스트의 첫 번째 <제목> 요소 노드 값을 대체합니다 :
예
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Italian";
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Italian";
»시도
예 설명 :
- 사용 loadXMLDoc을 () "에 Books.xml을 해당 xmldoc에"
- 첫 번째 텍스트 노드를 가져옵니다 <제목> 요소 노드
- 텍스트 노드를 변경하려면 nodeValue를 속성을 사용하여
당신은 할 수 있습니다 노드 변경 이상이 장에서 설명하는 노드 값을 변경에 대해 읽어합니다.