本例子是參考了一些網(wǎng)站上有關(guān)jsp 對(duì) xml 的操作的相關(guān)文檔,又結(jié)合了一些個(gè)人的體會(huì)。例子涉及的內(nèi)容是,開(kāi)發(fā)的一個(gè)企業(yè)內(nèi)部定餐系統(tǒng)后臺(tái)管理端的部分代碼,功能主要集中在對(duì)于餐館基本信息的管理。
//得到已有的記錄數(shù),給新增的餐館記錄設(shè)定唯一的遞增的id 屬性 int intNum=0; Element restNum=(Element)doc.getElementsByTagName("restaurants").item(0); intNum=Integer.parseInt(restNum.getAttributeNode("num").getNodeValue());
//新增節(jié)點(diǎn) Element newRestaurant=doc.createElement("restaurant");
Attr newArrId=doc.createAttribute("id"); //Attribute newArrId = new Attribute("id",String.valueOf(intNum)); textseg=doc.createTextNode(String.valueOf(intNum)); newArrId.setValue(String.valueOf(intNum)); newRestaurant.setAttributeNode(newArrId);
Element newName=doc.createElement("name"); textseg=doc.createTextNode(strName); newName.appendChild(textseg); newRestaurant.appendChild(newName);
Element newPhone=doc.createElement("phone"); textseg=doc.createTextNode(strPhone); newPhone.appendChild(textseg); newRestaurant.appendChild(newPhone);
Element newAddress=doc.createElement("address"); textseg=doc.createTextNode(strAddress); newAddress.appendChild(textseg); newRestaurant.appendChild(newAddress);