📄 addbook.java
字号:
import java.io.*;
import org.w3c.dom.*;
import org.w3c.dom.Node;
import org.xml.sax.*;
import javax.xml.parsers.*;
public class AddBook
{
String id = null;
String title = null;
String author = null;
public void setAll(String s1,String s2,String s3)
{
id = s1;
title = s2;
author = s3;
}
public void addBook(Document doc)
{
Element eBook = doc.createElement("book");
Element eId = doc.createElement("id");
Element eTitle = doc.createElement("title");
Element eAuthor = doc.createElement("author");
Text tId = doc.createTextNode(id);
Text tTitle = doc.createTextNode(title);
Text tAuthor = doc.createTextNode(author);
Node nId = eBook.appendChild(eId).appendChild(tId);
Node nTitle = eBook.appendChild(eTitle).appendChild(tTitle);
Node nAuthor = eBook.appendChild(eAuthor).appendChild(tAuthor);
Element root = doc.getDocumentElement();
Node nBook = root.appendChild(eBook);
}
public void printDOC(Document doc)
{
NodeList nl = doc.getElementsByTagName("*");
Element e;
int len;
len = nl.getLength();
for (int j=0;j < len;j++)
{
e = (Element)nl.item(j);
System.out.println(e.getTagName()+":"+e.getFirstChild().getNodeValue());
}
}
static public void main(String[] argv)
{
try
{
if (argv.length != 3)
{
System.err.println("格式: java AddBook 编号 书名 作者");
System.exit(1);
}
DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
DocumentBuilder domparser = dbfactory.newDocumentBuilder();
Document doc = domparser.parse(new File("library.xml"));
AddBook ab = new AddBook();
ab.setAll(argv[0],argv[1],argv[2]);
ab.addBook(doc);
ab.printDOC(doc);
}
catch (ParserConfigurationException p)
{
System.out.println(p.toString());
}
catch (SAXException s)
{
System.out.println(s.toString());
}
catch (IOException e)
{
System.out.println(e.toString());
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -