以下示範透過createNode()函式新增商品,並顯示新增後的結果:
<?xml version="1.0" encoding="GB2312" ?><shop>
<name>華聯</name>
<address>北京長安街-9999號</address>
<desc>連鎖超市</desc>
<telphone>123456789</telphone>
<cat id="food">
<goods id="food11"><name>food11</name><price>12.90</price><leaveword author="hahawen" date="2004-12-05">這個商品不錯</leaveWord></goods>
<goods id="food12"><name>new food12</name><price>22.10</price></goods>
<goods id="food13"><name>food13</name><price>100</price></goods>
</cat>
<cat><goods id="tel21"><name>tel21</name><price>1290</price></goods></cat>
<cat id="coat">
<goods id="coat31"><name>coat31</name><price>112</price></goods>
<goods id="coat32"><name>coat32</name><price>45</price></goods>
</cat>
<special id="hot"><goods><name>hot41</name><price>99</price></goods></special></shop>
接著示範透過removeNode()函式刪除商品,並顯示刪除後的結果:
<?xml version="1.0" encoding="GB2312" ?><shop>
<name>華聯</name>
<address>北京長安街-9999號</address>
<desc>連鎖超市</desc>
<telphone>123456789</telphone>
<cat id="food">
<goods id="food11"><name>food11</name><price>12.90</price><leaveword author="hahawen" date="2004-12-05">這個商品不錯</leaveWord></goods>
<goods id="food13"><name>food13</name><price>100</price></goods>
</cat>
<cat><goods id="tel21"><name>tel21</name><price>1290</price></goods></cat>
<cat id="coat">
<goods id="coat31"><name>coat31</name><price>112</price></goods>
<goods id="coat32"><name>coat32</name><price>45</price></goods>
</cat>
<special id="hot"><goods><name>hot41</name><price>99</price></goods></special></shop>
透過createNode()新增節點後,商品清單中多出了food12;再以removeNode()刪除後,該筆資料便從文件中消失。這兩個函式搭配使用,就能靈活維護XML文件內的商品結構。