
DOMElement::replaceChildren 함수를 사용하여 자식 요소를 교체할 때, 자식 요소의 속성을 유지하는 방법은 다음과 같습니다.
1. 자식 요소의 속성을 XML 문서에 직접 저장하는 방법: 자식 요소의 속성을 XML 문서에 직접 저장하여, DOMElement::replaceChildren 함수를 사용할 때도 속성이 유지됩니다.
#hostingforum.kr
php
$xml = new DOMDocument();
$xml->loadXML('');
$root = $xml->documentElement;
$child = $root->firstChild;
$child->setAttribute('id', '2');
$child->setAttribute('name', 'child2');
$root->replaceChild($xml->createElement('child'), $child);
echo $xml->saveXML();
2. 자식 요소의 속성을 DOMElement::replaceChildren 함수를 사용하기 전에 저장하는 방법: 자식 요소의 속성을 저장한 후, DOMElement::replaceChildren 함수를 사용하여 자식 요소를 교체할 수 있습니다.
#hostingforum.kr
php
$xml = new DOMDocument();
$xml->loadXML('');
$root = $xml->documentElement;
$child = $root->firstChild;
$attributes = array();
foreach ($child->attributes as $attribute) {
$attributes[$attribute->name] = $attribute->value;
}
$root->replaceChild($xml->createElement('child'), $child);
$child = $root->firstChild;
foreach ($attributes as $name => $value) {
$child->setAttribute($name, $value);
}
echo $xml->saveXML();
3. 자식 요소의 속성을 DOMElement::replaceChildren 함수를 사용한 후 다시 설정하는 방법: 자식 요소의 속성을 다시 설정하여, DOMElement::replaceChildren 함수를 사용한 후에도 속성이 유지됩니다.
#hostingforum.kr
php
$xml = new DOMDocument();
$xml->loadXML('');
$root = $xml->documentElement;
$child = $root->firstChild;
$root->replaceChild($xml->createElement('child'), $child);
$child = $root->firstChild;
$child->setAttribute('id', '2');
$child->setAttribute('name', 'child2');
echo $xml->saveXML();
자식 요소의 속성이 유지되는지 확인하는 방법은, 자식 요소의 속성을 XML 문서에 저장한 후, DOMElement::replaceChildren 함수를 사용하여 자식 요소를 교체한 후, XML 문서를 다시 읽어와 속성을 확인하는 것입니다.
#hostingforum.kr
php
$xml = new DOMDocument();
$xml->loadXML('');
$root = $xml->documentElement;
$child = $root->firstChild;
$root->replaceChild($xml->createElement('child'), $child);
$child = $root->firstChild;
$attributes = array();
foreach ($child->attributes as $attribute) {
$attributes[$attribute->name] = $attribute->value;
}
echo 'id: ' . $attributes['id'] . ', name: ' . $attributes['name'];
2025-05-25 21:37