js中使用DOM複製(複製)指定節點名資料到新的XML檔案中的代碼_javascript技巧

來源:互聯網
上載者:User
複製代碼 代碼如下:

<?php
/*
<?xml version="1.0" encoding="utf-8"?>
<article>
<item>
<title name="t1"></title>
<content>content1</content>
<pubdate>2009-10-11</pubdate>
</item>
<item>
<title name="t2">title2</title>
<content>content2</content>
<pubdate>2009-11-11</pubdate>
</item>
</article>
*/
/*
使用DOM複製(複製)指定節點名資料到新的XML檔案中 ,用到三個類的相關知識點 : 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 '<br />********************************<br />';
}
}
if(!function_exists('cp_xml')) {
/*
* 複製指定節點元素資訊到新XML檔案中
* @param $dom : 源XML檔案的DOM對象
* @param $newdom : 新XML檔案的DOM對象
* @param $node: 指定複製的節點元素名
* @param $file: 新產生的XML檔案名稱
* @param $attribute: 指定複製的節點元素的屬性名稱
* @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<count($clone); $i++) {
$title = $newdom->createElement($clone[$i]->nodeName,$clone[$i]->nodeValue);
$root->appendChild($title);
if(count($attr)>0 && !empty($attribute)) {
//建立屬性名稱
$aname = $newdom->createAttribute($attribute);
$title->appendChild($aname);
//傳遞屬性值
$aval = $newdom->createTextNode($attr[$i]);
$aname->appendChild($aval);
}
}
$newdom->save($file);
}
}
if(file_exists("test10_12.xml")) {
//執行個體一
$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);
//執行個體二
$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');
}
?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.