Home > Web Front-end > JS Tutorial > Code to use DOM to copy (clone) specified node name data to a new XML file in js_javascript skills

Code to use DOM to copy (clone) specified node name data to a new XML file in js_javascript skills

WBOY
Release: 2016-05-16 18:04:22
Original
1154 people have browsed it
Copy code The code is as follows:

/*




content1
2009-10-11


title2
content2
2009-11-11

< /article>
*/
/*
Use DOM to copy (clone) the specified node name data into a new XML file, using the relevant knowledge points of three classes: DOMDocument - DOMNodeList - DOMNode
1.DOMNodeList DOMDocument::getElementsByTagName ( string $name )
2.DOMNode DOMNodelist::item ( int $index )
3.DOMNode DOMNode::cloneNode ([ bool $deep ] )
*/
if(!function_exists('l')) {
function l() {
echo '
********************** ***************
';
}
}
if(!function_exists('cp_xml')) {
/*
* Copy the specified node element information to the new XML file
* @param $dom: DOM object of the source XML file
* @param $newdom: DOM object of the new XML file
* @param $node: Specify the name of the copied node element
* @param $file: The name of the newly generated XML file
* @param $attribute: Specify the attribute name of the copied node element
* @return void
*/
function cp_xml($dom,$newdom,$node,$file,$attribute = '') {
$contents = $dom->getElementsByTagName($node);
$clone = array();
$attr = array();
for($i = 0 ; $i<$contents->length; $i ) {
$node = $contents-> item($i);
if($node->hasAttributes() && !empty($attribute)) {
$attr[] = $node->getAttribute($attribute);
}
$clone[] = $node->cloneNode(true);
}
var_dump($attr);
$root = $newdom->createElement('root');
$newdom->appendChild($root);
for($i = 0 ; $i$title = $newdom->createElement( $clone[$i]->nodeName,$clone[$i]->nodeValue);
$root->appendChild($title);
if(count($attr)>0 && !empty($attribute)) {
//Create attribute name
$aname = $newdom->createAttribute($attribute);
$title->appendChild($aname);
//Pass attribute value
$aval = $newdom->createTextNode($attr[$i]);
$aname->appendChild($aval);
}
}
$newdom->save($file);
}
}
if(file_exists("test10_12.xml")) {
//Example 1
$dom = new DOMDocument();
$newdom = new DOMDocument('1.0','utf-8');
$dom->load("test10_12.xml");
$node = 'content' ;
$file = '11_1.xml';
cp_xml($dom,$newdom,$node,$file);
//Example 2
$dom = new DOMDocument();
$newdom = new DOMDocument('1.0','utf-8');
$dom->load("test10_12.xml");
$node = 'title';
$ file = '11_2.xml';
cp_xml($dom,$newdom,$node,$file,$attribute = 'name');
}
?>
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template