import my.com.vo.Company;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import java.io.FileOutputStream;
import java.io.Writer;
import java.util.List;
public class CpService {
public static void addCp(Company company) throws Exception {
/*
* 1、建立解析器
* 2、得到document
* 3、擷取根節點
* 4、再根節點上面建立cp标簽
* 5、在cp标簽上面依次添加cpid,cpname,cpaddr
* 6、在cpid,cpname,cpaddr。
*
* */
//建立解析器
SAXReader saxReader = new SAXReader();
//得到Document
Document document = saxReader.read("src/company.xml");
//得到根節點
Element root = document.getRootElement();
//在根節點上面添加stu
Element cp = root.addElement("cp");
//在标簽上面添加标簽
Element cpid1 = cp.addElement("cpid");
Element cpname1 = cp.addElement("cpname");
Element cpaddr1 = cp.addElement("cpaddr");
//添加值
cpid1.setText(company.getCpid());
cpname1.setText(company.getCpname());
cpaddr1.setText(company.getCpaddr());
//回寫xml
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("src/company.xml"), format);
xmlWriter.write(document);
xmlWriter.close();
}
//根據學生id删除
public static void delCp(String cpid ) throws Exception {
/*
* 1、建立解析器
* 2、得到document
* 3、擷取所有id
*
* 使用xpath
* 4、周遊list集合
* 5、判斷集合裡面的id和傳遞的id是否相同
* 6、相同即可删除id所在cp
* */
//建立解析器
SAXReader saxReader = new SAXReader();
//得到document
Document document = saxReader.read("src/company.xml");
//擷取所有id xpath://id
List<Node> list = document.selectNodes("//cpid");
//周遊list集合
for (Node node : list) {
String cpidv = node.getText();
if (cpidv.equals(cpid)) {
Element cp = node.getParent();
Element company = cp.getParent();
company.remove(cp);
} //回寫xml
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("src/company.xml"), format);
xmlWriter.write(document);
xmlWriter.close();
}
}
/* //查詢根據學生id
public static Company getCp(String cpid) {
*//*
* 1、建立解析器
* 2、得到document
* 3、擷取到所有id
* 4、傳回list集合 周遊List集合
* 5、得到每一個id的節點
* 6、id節點的值
* 7、判斷id的值和傳遞的id值是否相同
* *//*
}*/
}