第一类:JAXP - java api for xml process
1.Dom
2.sax
3.StAx
第二种:第三方框架
Dom4j
Jaxp中所有解析方式的主要解析类,都是通过工厂模式获取到的。
第一种:jaxp-dom
@Test
public void jaxpDom() throws Exception{
DocumentBuilder db=DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document dom = db.parse (DomDemo.class.getClassLoader()
.getResourceAsStream("users.xml"));
NodeList nl = dom.getElementsByTagName("user");
int len = nl.getLength();
for(int i=0;i<len;i++){
Element el =(Element) nl.item(i);
String id = el.getAttribute("id");
String name = el.getElementsByTagName("name")
.item(0).getTextContent();
String age = el.getElementsByTagName("age")
.item(0).getTextContent();
System.err.println("id:"+id+","+name+","+age);
}
}
第二步:jaxp-sax
<wj:web-app version="2.5"
xmlns:wj[W1]="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<wj:display-name></wj:display-name>
<wj:filter>[W2]
<wj:filter-name></wj:filter-name>
<wj:filter-class></wj:filter-class>
@Test
public void jaxpSax() throws Exception{
SAXParser sax = SAXParserFactory.newInstance().newSAXParser();
sax.parse(in,new DefaultHandler(){
private boolean nameOrAge=false;
/**
* 某个元素开始了<somename>
*/
@Override
public void startElement(String uri,String localName,
String qName,Attributes attr) throws SAXException {
if(qName.equals("user")){
System.err.println(attr.getValue("id"));
}else if(qName.equals("name") || qName.equals("age")){
nameOrAge=true;
}
}
/**
* 某个元素的结束</somename>
*/
@Override
public void endElement(String uri,String qName)
throws SAXException {
if(qName.equals("name") || qName.equals("age")){
nameOrAge=false;
}
}
/**
* 字符的开始<>someValue</>
*/
@Override
public void characters(char[] ch,int start,int length)
throws SAXException {
if(nameOrAge){
String value = new String(ch,start,length);
System.err.println(value);
}
}
});
}
第三步:jaxp-StAX
/**
* pull解析
* javax.xml.stream
*/
@Test
public void jaxpStax() throws Exception{
XMLStreamReader xml =
XMLInputFactory.newInstance().createXMLStreamReader(in);
while(tag!=XMLStreamReader.END_DOCUMENT[W5]){
if(tag==XMLStreamReader.START_ELEMENT[W6]){
if(xml.getLocalName().equals("user")[W7]){
String id = xml.getAttributeValue(0);
System.err.println(id);
}
if(xml.getLocalName().equals("name")){
String name = xml.getElementText();
System.err.println("name:"+name);
}
if(xml.getLocalName().equals("age")){
String age = xml.getElementText();
System.err.println("age:"+age);
}
}
tag = xml.next();
}
}
第四种:dom4j
代码:
@Test
public void testDom4j() throws Exception{
SAXReader reader = new SAXReader();
org.dom4j.Document dom =reader.read(in);
List<org.dom4j.Element> list= dom.selectNodes("//user");
for(org.dom4j.Element el:list){
String id=el.attributeValue("id");
String name = el.elementText("name");
String age = el.element("age").getText();
System.err.println(id+","+age);
}
}