XML学习笔记
这篇文档是李兴华老师讲解JSP时XML部分的内容。我看完视频后做的笔记。感觉笔记清楚,有兴趣的可以看下。本来有图片,但图片无法复制。
一.DOC方式处理XML文件
1.1XML文件的解析
准备解析的XML文件:
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <properties>
<info> <comment>Area Info</comment> <entry>Ye</entry> </info>
<info> <comment>Liu Info</comment> <entry>liu</entry> </info> </properties> |
具体解析代码:
public static void main(String[] args) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new File("D:" + File.separator + "area.xml")); NodeList nl = doc.getElementsByTagName("info"); for(int i = 0; i < nl.getLength(); i++) { Element e = (Element) nl.item(i); System.out.println("comment:" + e.getElementsByTagName("comment").item(0).getFirstChild().getNodeValue()); System.out.println("entry:" + e.getElementsByTagName("entry").item(0).getFirstChild().getNodeValue()); } } |
1.1XML文件的生成
生成XML文件
public static void main(String[] args) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); //新建文档对象 //创建节点 Element info = doc.createElement("info"); Element name = doc.createElement("name"); Element age = doc.createElement("age"); //建立节点关系 name.appendChild(doc.createTextNode("Liu")); age.appendChild(doc.createTextNode("21")); info.appendChild(name); info.appendChild(age); doc.appendChild(info); //输出XML文件 TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("D:" + File.separator + "info.xml")); t.transform(source, result); } |
生成的XML文件:
<?xml version="1.0" encoding="UTF-8"?> <info> <name>Liu</name> <age>21</age> </info> |
二.XML文件处理方式SAX
1.1 SAX只能读取XML文件
1.XML文件
<?xml version="1.0" encoding="UTF-8"?> <info> <name>Liu</name> <age>21</age> </info> |
2.首先创建解析的SAX类
import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler;
class MySax extends DefaultHandler { public void startDocument() throws SAXException { System.out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" >"); }
public void startElement(String url, String localName, String qName, Attributes attributes) throws SAXException { System.out.print("<" + qName ); //设置属性 for(int i = 0; i < attributes.getLength(); i++) { System.out.print(" " + attributes.getQName(i) + "=\"" + attributes.getValue(i) + "\""); } System.out.print(">"); }
public void characters(char[] ch, int start, int length) throws SAXException { System.out.print(new String(ch, start, length)); } public void endElement(String url, String localName, String qName) throws SAXException { System.out.print("</" + qName + ">" ); }
public void endDocument() throws SAXException { System.out.println("\n=== End ===="); } } |
1.2解析
public class XMLTest {
public static void main(String[] args) throws Exception { SAXParserFactory spfactory = SAXParserFactory.newInstance(); SAXParser sp = spfactory.newSAXParser(); sp.parse(new File("D:" + File.separator + "info.xml"), new MySax()); } } |
解析后XML文件显示结果:
<?xml version="1.0" encoding="UTF-8" > <info><name>Liu</name><age>21</age></info> === End ==== |
三.JDOC处理XML文件
首先到 www.jdom.org上下载 jdom.jar 文件。
然后将jdom.jar文件导入到项目中。也可以将存放jar文件路径添加到 ClassPath变量中。 路径格式: D:\Codes\workspace\MyProgram\jdom-2.0.5.jar
3.1 JDOC生成XML文件
具体代码:
import java.io.File; import java.io.FileOutputStream;
import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.output.XMLOutputter;
public class XMLTest {
public static void main(String[] args) throws Exception { Element info = new Element("info"); Element name = new Element("name"); Element age = new Element("age"); Attribute id = new Attribute("id", "ye"); Document doc = new Document(info); name.setText("Stream"); name.setAttribute(id); age.setText("21"); info.addContent(name); info.addContent(age); XMLOutputter out = new XMLOutputter(); out.setFormat(out.getFormat().setEncoding("gbk")); out.output(doc, new FileOutputStream("D:" + File.separator + "info_jdom.xml")); } } |
生成的XML文件
<?xml version="1.0" encoding="GBK"?> <info> <name id="ye">Stream</name> <age>21</age> </info> |
3.2 JDOC读取XML文件
读取以上例子生成的XML文件
public static void main(String[] args) throws Exception { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build("D:" + File.separator + "info_jdom.xml"); Element root = doc.getRootElement(); List<Element> list = root.getChildren(); for(int i = 0; i < list.size(); i++) { Element e = list.get(i); System.out.println(e.getName() + ":" + e.getValue()); } } |
递归读取XML中节点信息
public static void print(Element e, int i) { StringBuffer s = new StringBuffer(); for(int x = 0; x < i; x++) { s.append(" "); } List<Element> childlist = null; childlist = e.getChildren(); if (childlist.size() > 0) { i++; System.out.print(s.toString() + e.getName() + " "); List<Attribute> att = e.getAttributes(); for(int j = 0; j < att.size(); j++) { Attribute a = att.get(j); System.out.print(a.getName() + "=" + a.getValue() ); } System.out.println(":"); for(int j = 0; j < childlist.size(); j++) { Element ce = childlist.get(j); print(ce, i); } } else { System.out.print(s.toString() + e.getName() + " "); List<Attribute> att = e.getAttributes(); for(int j = 0; j < att.size(); j++) { Attribute a = att.get(j); System.out.print(a.getName() + "=" + a.getValue() ); } System.out.println(" :" + e.getValue()); } } |
四.DOM4J处理XML文件
首先要下载dom4j-1.6.1.jar文件。在网站 http://sourceforge.net/ 中标记的位置输入 dom4j,搜索。下载,导入到项目中。
4.1XML文件的生成
import java.io.File; import java.io.FileOutputStream;
import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter;
public class XMLTest {
public static void main(String[] args) throws Exception { Document doc = DocumentHelper.createDocument(); Element info = doc.addElement("info"); Element name = info.addElement("name"); Element age = info.addElement("age"); name.setText("Hi"); age.setText("21"); OutputFormat format = new OutputFormat(); format.setEncoding("UTF-8"); XMLWriter write = new XMLWriter(new FileOutputStream( new File("D:" + File.separator + "info_dom4j.xml")), format); write.write(doc); write.close(); } } |
生成的XML文件:
<?xml version="1.0" encoding="UTF-8"?> <info> <name>Hi</name> <age>21</age> </info> |
4.2 DOM4J解析XML文件
解析代码:
import java.io.File; import java.util.Iterator;
import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader;
public class XMLTest {
public static void main(String[] args) throws Exception { File file = new File("D:" + File.separator + "info_dom4j.xml"); SAXReader reader = new SAXReader(); Document doc = reader.read(file); Element root = doc.getRootElement(); Iterator iter = root.elementIterator(); while(iter.hasNext()) { Element e = (Element) iter.next(); System.out.println(e.getName() + ":" + e.getText()); } } } |
五.JavaScript操作XML文件
代码:
<!DOCTYPE html > <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=GBK" /> <title>JavaScript Test</title> <script type="text/javaScript"> function func() { var id = new Array(1,2,3); var value = new Array("北京","上海","深圳"); var select = document.getElementById("area"); select.length = 1; select.options[0].selected = true; for(var i = 0; i < id.length; i++) { var option = document.createElement("option"); option.setAttribute("value",id[i]); option.appendChild(document.createTextNode(value[i])); select.appendChild(option); } } </script> </head> <body οnlοad="func()"> <form action="" method="posth" name="myform" > <select name="area" id="area" > <option value="0">没有地区</option> </select> </form> </body> </html> |