TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
编写sax过滤器一般继承XMLFilterImpl即可,
下面的程序给book元素加id属性:
<?xml version="1.0" encoding="GB2312" ?>
<booklist>
<book>
<书名>21世纪计算机概论</书名>
<定价>13$</定价>
<作者>江高举</作者>
<作者>刘致仪</作者>
<备注>no</备注>
</book>
</booklist>
import org.xml.sax.helpers.*;
import org.xml.sax.*;
import java.io.IOException;
import java.util.*;
??
public class MainSaxApp {
public static void main (String[] args){
try {
String parserClass = "org.apache.crimson.parser.XMLReaderImpl";//自己喜欢的分析器
XMLReader reader = XMLReaderFactory.createXMLReader(parserClass);
DataFilter filter = new DataFilter();//sax过滤器
filter.setParent(reader);//此后的解析由过滤器处理
filter.setContentHandler(new DataProcessor());
filter.parse("booklist.xml");
} catch (IOException ioe) {
System.out.println("IO Exception: "+ioe.getMessage());
} catch(SAXException se) {
System.out.println("SAX Exception: "+se.getMessage());
}
}
}
class DataFilter extends XMLFilterImpl
{
int id=1;
private Set ids;
public void startElement (String namespaceUri, String localName, String qualifiedName, Attributes attributes) throws SAXException {
if(localName=="book"){//给book元素加属性
AttributesImpl newAttributes=new AttributesImpl();
String idValues=makeID();
newAttributes.addAttribute(" ","id","id","ID",idValues);
attributes=newAttributes;
}
super.startElement(namespaceUri, localName, qualifiedName, attributes);
}
public void startDocument(){
ids=new HashSet();
id=1;
}
public String makeID(){
while(ids.contains("_"+id)) id++;
ids.add("_"+id);
return "_"+id;
}
}
class DataProcessor extends DefaultHandler{
public void startElement (String namespaceUri, String localName,String qualifiedName, Attributes attributes) {
System.out.println(localName);
for(int i=0; i<attributes.getLength(); i++)
System.out.println(attributes.getLocalName(i) +" = " + attributes.getValue(i) + ".");
}
}
程序结果:
C:java>java MainSaxApp
booklist
book
id = _1.
书名
定价
作者
作者
备注
function TempSave(ElementID)
{
CommentsPersistDiv.setAttribute("CommentContent",document.getElementById(ElementID).value);
CommentsPersistDiv.save("CommentXMLStore");
}
function Restore(ElementID)
{
CommentsPersistDiv.load("CommentXMLStore");
document.getElementById(ElementID).value=CommentsPersistDiv.getAttribute("CommentContent");
} |
|