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值是否相同
* *//*
}*/
}