代码拉取完成,页面将自动刷新
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();
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。