问题描述
<?xml version =1.0encoding =UTF- 8\" >?;
<游戏>
<移动>
< turn> 2< / turn>
< piece nr =1/>
< turn> 4< / turn>
< piece nr =1/>
< /移动>
< /游戏>
我正在编写一个Java程序,将XML文件作为输入,然后使用SAX和SAX过滤器并计算:
- 转动元素的内容之和(这里= 6)
- 然后我想要使用一个SAX过滤器来生成一个输出XML文件,这个文件就是这个文件的一部分(这里是= 2)
与输入相同,但有一个额外的元素:
< s:statistics>
< s:turn-total> 6< / s:turn-total>
< s:件数> 2< / s:件数>
< / s:统计信息>
前缀
s
是对。
我的程序如此很远是:
pre $public class test {
public static void main(String [] args)throws Exception {
if(args.length!= 2){
System.err.println(error);
System.exit(1);
}
String xmlInput = args [0];
String filteredXML = args [1];
test test1 = new test();
test1.sax(xmlInput,filteredXML);
}
private void sax(String gameXML,String filteredGameXML)throws Exception {
FileInputStream fis = new FileInputStream(gameXML);
InputSource is = new InputSource(fis);
XMLReader xr = XMLReaderFactory.createXMLReader();
XMLFilter xf = new MyFilter();
xf.setParent(xr);
xr = xf;
xr.parse(is);
xr.setFeature(http://xml.org/sax/features/namespaces,true);
DefaultHandler handler = new DefaultHandler();
xr.setContentHandler(handler);
}
private class MyFilter extends XMLFilterImpl {
StringBuffer buffer;
int temp = 0;
int sum = 0;
String ff;
int numof = 0;
private MyFilter(){}
$ b @Override
public void startDocument()throws SAXException {
System.out.println(START DOCUMENT);
numof = 0;
$ b $ public void startElement(String namespaceURI,String localName,String name,Attributes attributes)throws SAXException {
if(localName.equals(turn)){
buffer = new StringBuffer();
if(piece.equals(name)){
numof ++;
$ b $ public void characters(char [] ch,int start,int length)throws SAXException {
String s = new String(ch,start,长度);
if(buffer!= null){
buffer.append(s);
$ b $ public void endElement(String uri,String localName,String name)throws SAXException {
if(buffer!= null){
FF = buffer.toString();
temp = Integer.valueOf(ff);
sum = sum + temp;
}
buffer = null;
}
public void endDocument()throws SAXException {
System.out.println(END DOCUMENT);
System.out.println(sum of turn:+ sum);
System.out.println(sum of piece:+ numof);
$ b $ / code>我做下一步?
解决方案您的XMLFilter
应委托给另一个ContentHandler
,它基于sax事件序列化文档。
SAXTransformerFactory factory = SAXTransformerFactory)TransformerFactory.newInstance();
TransformerHandler serializer = factory.newTransformerHandler();
结果结果=新的StreamResult(...);
serializer.setResult(result);
XMLFilterImpl filter = new MyFilter();
filter.setContentHandler(serializer);
XMLReader xmlreader = XMLReaderFactory.createXMLReader();
xmlreader.setFeature(http://xml.org/sax/features/namespaces,true);
xmlreader.setFeature(http://xml.org/sax/features/namespace-prefixes,true);
xmlreader.setContentHandler(filter);
xmlreader.parse(new InputSource(...));
您的回调应委派给
super
执行,将事件转发到序列化ContentHandler
。public void startElement (String namespaceURI,String localName,String qName,Attributes atts)throws SAXException {
super.startElement(namespaceURI,localName,qName,atts);
$ p $endElement
public void endElement(String namespaceURI,String localName,String qName)throws SAXException {
super.endElement(namespaceURI,localName,qName);
if(game.equals(localName)){
super.startElement(,statistics,statistics,new AttributesImpl());
char [] chars = String.valueOf(num).toCharArray();
super.characters(chars,0,chars.length);
super.endElement(,statistics,statistics);
}
...
}
I have an XMl file that looks like:
<?xml version="1.0" encoding="UTF-8"?> <game > <moves> <turn>2</turn> <piece nr="1" /> <turn>4</turn> <piece nr="1" /> </moves> </game>
I am writing a Java program that takes the XML file as input then parses it with SAX and SAX filter and computes:
- the sum of the content of turn element (here=6)
- the number of piece elements (here=2)
Then I want to use a SAX filter in order to generate an output XML file that are the same as the input one but with an additional element like:
<s:statistics> <s:turn-total>6</s:turn-total> <s:piece-count>2</s:piece-count> </s:statistics>
The prefix
s
is a reference to a namespace.My program so far is:
public class test{ public static void main(String[] args) throws Exception { if (args.length != 2) { System.err.println("error "); System.exit(1); } String xmlInput = args[0]; String filteredXML = args[1]; test test1 = new test(); test1.sax(xmlInput, filteredXML); } private void sax(String gameXML, String filteredGameXML)throws Exception{ FileInputStream fis = new FileInputStream( gameXML); InputSource is = new InputSource(fis); XMLReader xr = XMLReaderFactory.createXMLReader(); XMLFilter xf = new MyFilter(); xf.setParent(xr); xr = xf; xr.parse(is); xr.setFeature("http://xml.org/sax/features/namespaces", true); DefaultHandler handler = new DefaultHandler(); xr.setContentHandler(handler); } private class MyFilter extends XMLFilterImpl{ StringBuffer buffer; int temp=0; int sum=0; String ff; int numof=0; private MyFilter() {} @Override public void startDocument() throws SAXException { System.out.println( "START DOCUMENT" ); numof=0; } public void startElement(String namespaceURI, String localName, String name, Attributes attributes) throws SAXException{ if(localName.equals("turn")){ buffer=new StringBuffer(); } if("piece".equals(name)){ numof++; } } public void characters(char[] ch, int start, int length) throws SAXException { String s=new String(ch, start, length); if(buffer!=null){ buffer.append(s); } } public void endElement(String uri, String localName, String name)throws SAXException { if(buffer!=null ){ ff=buffer.toString(); temp=Integer.valueOf(ff); sum=sum+temp; } buffer=null; } public void endDocument() throws SAXException { System.out.println( "END DOCUMENT" ); System.out.println("sum of turn: "+ sum); System.out.println("sum of piece: "+ numof); } } }
What should I do next?
解决方案Your
XMLFilter
should delegate to anotherContentHandler
that serializes the document based on the sax events.SAXTransformerFactory factory = (SAXTransformerFactory)TransformerFactory.newInstance(); TransformerHandler serializer = factory.newTransformerHandler(); Result result = new StreamResult(...); serializer.setResult(result); XMLFilterImpl filter = new MyFilter(); filter.setContentHandler(serializer); XMLReader xmlreader = XMLReaderFactory.createXMLReader(); xmlreader.setFeature("http://xml.org/sax/features/namespaces", true); xmlreader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); xmlreader.setContentHandler(filter); xmlreader.parse(new InputSource(...));
Your callback should delegate to the
super
implementation, which forwards the events to the serializingContentHandler
.public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { super.startElement(namespaceURI, localName, qName, atts); ... }
In your
endElement
callback you can check if your are at the final closing tag and add additional sax events.public void endElement(String namespaceURI, String localName, String qName) throws SAXException { super.endElement(namespaceURI, localName, qName); if ("game".equals(localName)) { super.startElement("", "statistics", "statistics", new AttributesImpl()); char[] chars = String.valueOf(num).toCharArray(); super.characters(chars, 0, chars.length); super.endElement("", "statistics", "statistics"); } ... }
这篇关于使用SAX过滤器将新元素插入XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-28 01:08