加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
AddXml.java 2.11 KB
一键复制 编辑 原始数据 按行查看 历史
package homework;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Scanner;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class AddXml {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
SAXReader reader = new SAXReader();
String s1 = null;
String s2 = null;
try {
Document doc = reader.read(new File("work\\products.xml"));
Element root = doc.getRootElement();
System.out.println("请输入新增加的商品号:");
String sch = sc.next();
System.out.println("请输入商品名:");
String ename = sc.next();
List<Element> list = doc.selectNodes("/shop/product");
for (Element e : list) {
s1 = e.selectSingleNode("itemno").getText();
s2 = e.selectSingleNode("name").getText();
if ((s1.equals(sch)) || (s2.equals(ename))) {
System.out.println("商品号或商品名称重复,添加失败!");
return;
}
}
Element newb = root.addElement("product");
Element eitemno = newb.addElement("itemno");
eitemno.setText(sch);
Element name = newb.addElement("name");
name.setText(ename);
System.out.println("请输入是否是打折商品 true/false:");
newb.addAttribute("discount", sc.next());
System.out.println("请输入厂商地址:");
newb.addAttribute("factoryaddr", sc.next());
System.out.println("请输入商品价格:");
Element price = newb.addElement("price");
price.setText(sc.next());
System.out.println("请输入库存数:");
Element stockcount = newb.addElement("stockcount");
stockcount.setText(sc.next());
System.out.println("请输入计价单位:");
Element unit = newb.addElement("unit");
unit.setText(sc.next());
OutputFormat format = OutputFormat.createCompactFormat();
format.setEncoding("utf-8");
XMLWriter xm = new XMLWriter(new FileOutputStream("products.xml"), format);
xm.write(doc);
xm.close();
System.out.println("新商品添加成功");
return;
} catch (Exception e) {
e.printStackTrace();
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化