Sax 解析 XML文件

1. 解析文件格式

company.xml 写道
<?xml version='1.0' encoding='UTF-8'?>
<content>
<company>
<jydm>DJI</jydm>
<jsp>14719.46</jsp>
<rzdf>1.05</rzdf>
</company>
<company>
<jydm>HSI</jydm>
<jsp>21806.61</jsp>
<rzdf>-1.08</rzdf>
</company>
</content>

 

2. 实体类

Company.java 写道
public class Company {
private String jydm;
private String jsp;
private String rzdf;
public String getJydm() {
return jydm;
}
public void setJydm(String jydm) {
this.jydm = jydm;
}
public String getJsp() {
return jsp;
}
public void setJsp(String jsp) {
this.jsp = jsp;
}
public String getRzdf() {
return rzdf;
}
public void setRzdf(String rzdf) {
this.rzdf = rzdf;
}
@Override
public String toString() {
StringBuilder buf=new StringBuilder();
buf.append("company[jydm=").append(jydm).append(",jsp=").append(jsp).append(",rzdf=").append(rzdf).append("]");
return buf.toString();
}
}

 3. 解析类

CompanyParse.java 写道
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 CompanyParse extends DefaultHandler {
private List<Company> companys = null;
private Company company = null;
private String preTag = null;

@Override
public void startDocument() throws SAXException {
companys = new ArrayList<Company>();
}

@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if ("company".equals(qName)) {
company = new Company();
}
preTag = qName;
}

@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if ("company".equals(qName)) {
companys.add(company);
company = null;
}
preTag = null;

}

@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (preTag != null) {
String content = new String(ch, start, length);
if ("jydm".equals(preTag)) {
company.setJydm(content);
} else if ("jsp".equals(preTag)) {
company.setJsp(content);
} else if ("rzdf".equals(preTag)) {
company.setRzdf(content);
}
}
}

public List<Company> getCompanys() {
return companys;
}

public static void main(String[] args) throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
CompanyParse handler = new CompanyParse();
parser.parse("company.xml", handler);
for (Company comp : handler.getCompanys()) {
System.out.println(comp);
}
}
}

 4. 运行结果

company[jydm=DJI,jsp=14719.46,rzdf=1.05]

company[jydm=HSI,jsp=21806.61,rzdf=-1.08]

你可能感兴趣的:(sax xml)