<?xml version = "1.0" encoding="utf-8"?> <disks> <disk name=‘c‘> <name>系统盘</name> <size>10G</size> <directory>4</directory> <file>100</file> </disk> <disk name=‘d‘> <name>工作盘</name> <size>10G</size> <directory>3</directory> <file>200</file> </disk> </disks> <!-- 一定存在结尾和开始标签 --> |
点击*.xml文件,右键---open with---web brower--浏览器打开
右键
---properties---location--(C:\Users\lrq\Workspaces\MyEclipse 10\Corejava\src\com\briup\xml\disk.xml)
两种类:
Sax解析 从上到下能取到一次
public abstract class SAXParserFactory extends Object |
发现是抽象类,抽象类首先找到他的子类或者找到他的静态方法
SAXParserFactory
public abstract SAXParser newSAXParser() throws ParserConfigurationException, |
SAXParser
public void parse(File f, DefaultHandler dh) throws SAXException, 使用指定的 DefaultHandler 将指定文件的内容解析为 XML。
|
package com.briup.xml; import java.io.File; import javax.xml.parsers.ParserConfigurationException; 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; public class DiskSax { public static void main(String[] args) { // 保证xml是否能读到 // SaxParserFactory 解析工厂 SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser paser= factory.newSAXParser(); // 调用parse方法进行解析 File file = new File("src/com/briup/xml/disk.xml"); paser.parse(file,new MyHandler()); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
} class MyHandler extends DefaultHandler{
// 1表示开始标签名称 // 2 属性标签 @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // System.out.println("<"+localName+">"); System.out.print("<"+qName); for(int i =0;i<attributes.getLength();i++){ // 获取标签名称 String qName1= attributes.getQName(i); String value = attributes.getValue(qName1); System.out.print(" "+qName1+"="+value+"‘"); } System.out.print(">"); }
@Override public void endElement(String uri, String localName, String qName) throws SAXException { System.out.print("</"+qName+">");
} @Override public void characters(char[] ch, int start, int length) throws SAXException { System.out.print(new String(ch, start, length)); }
} |
<disks> <disk name=c‘> <name>系统盘</name> <size>10G</size> <directory>4</directory> <file>100</file> </disk> <disk name=d‘> <name>工作盘</name> <size>10G</size> <directory>3</directory> <file>200</file> </disk> </disks> |
编写Student.xml文件
<?xml version="1.0" encoding="utf-8"?> <students> <student id="1"> <name>tom</name> <age>20</age> <gender>male</gender> </student> <student id="2"> <name>jack</name> <age>21</age> <gender>male</gender> </student> <student id="3"> <name>rose</name> <age>20</age> <gender>female</gender> </student>
</students> |
创建Student类是为了将Student.xml文件内容封装到Student类里面。
package com.briup.xml; public class Student { private int id ; private String name ; private int age; private String gender ; public Student(int id, String name, int age, String gender) { super(); this.id = id; this.name = name; this.age = age; this.gender = gender; } public Student() {} public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } @Override public String toString() { return "id:"+id+"name:"+name+"age:"+age+"gender:"+gender; } } |
解析xml文件
1.sax方法
public abstract class SAXParserFactory extends Object 定义工厂 API,使应用程序能够配置和获取基于 SAX 的解析器以解析 XML 文档。 |
package com.briup.xml; import java.io.File; import java.util.ArrayList; import java.util.List; 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; //注意这个包不要抛错了 public class StudentSax { public static void main(String[] args) { //首先需要创建SAX工程,接受一个factory实例 SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser parser = factory.newSAXParser(); File file = new File("src/com/briup/xml/student.xml") ; MyHander2 mh = new MyHander2(); parser.parse(file, mh); List<Student> list = mh.list; for(Student List1:list){ System.out.println(List1); } } catch (Exception e) { e.printStackTrace(); }
} } class MyHander2 extends DefaultHandler{ private String tagName; Student student; List<Student> list = new ArrayList<Student>(); @Override public void characters(char[] ch, int start, int length) throws SAXException { String str = new String(ch,start,length) ; if("name".equals(tagName)){ student.setName(str); }else if("age".equals(tagName)){ student.setAge(Integer.parseInt(str)); }else if("gender".equals(tagName)){ student.setGender(str); // System.out.println(student); }
}
@Override public void endElement(String uri, String localName, String qName) throws SAXException { if(qName.equals("student")){ list.add(student); } tagName = null; }
// qName是标签名称 @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if("student".equals(qName)){ String id = attributes.getValue("id"); student = new Student(); student.setId(Integer.parseInt(id)); // System.out.println(student); }
tagName = qName; }
} |
2.xml使用dom解析
package com.briup.xml; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class StudentDOM { public static void main(String[] args) { List<Student> list= new ArrayList<Student>();
// 解析器工厂 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = factory.newDocumentBuilder(); File file = new File("src/com/briup/xml/student.xml"); // getElementByTagName(tagName) Document document = builder.parse(file); NodeList nl = document.getElementsByTagName("student"); // getLength:获取长度,便厉得到node对象 for(int i = 0;i < nl.getLength();i++){ Node n =nl.item(i); Element e = (Element)n; String id = e.getAttribute("id"); Student student = new Student(); student.setId(Integer.parseInt(id)); NodeList nl2 = n.getChildNodes(); for(int j=0;j<nl2.getLength();j++){ Node n2=nl2.item(j); // 获取标签名称 if(n2.getNodeName().equals("name")){ // 获取name标签内容 String name = n2.getTextContent(); student.setName(name); } if(n2.getNodeName().equals("age")){ // 获取age标签内容 int age =Integer.parseInt(n2.getTextContent()); student.setAge(age); } if(n2.getNodeName().equals("gender")){ // 获取gender标签内容 String gender = n2.getTextContent(); student.setGender(gender); System.out.println(student); } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
原文:http://www.cnblogs.com/xiaoxuesherry/p/5686548.html