<root>
<parent>
<child1> 30</child1>
<child2> 30</child2>
<child3> 30</child3>
</parent>
<parent>
<child1> 20</child1>
<child2> 30</child2>
<child3> 30</child3>
</parent>
<parent>
<child1> 30</child1>
<child2> 30</child2>
<child3> 30</child3>
</parent>
</root>
我对编码和sax解析的世界都很陌生。 考虑上面的XML,我需要的是。 ..基于标签child1的值,如果它大于20,那么我只想解析剩余的子标签(child2和child3),否则我想继续下一个父标签。
任何人都可以建议这样做的理想方式是什么?
答案 0 :(得分:1)
类似的东西:
...
private boolean skipChildren;
private StringBuilder buf = new StringBuilder();
...
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equals("parent")) {
skipChildren = false;
...
} else if (qName.equals("child1")) {
buf.setLength(0);
...
} else if (qName.startsWith("child")) {
if (!skipChildren) {
buf.setLength(0);
...
}
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equals("parent")) {
...
} else if (qName.equals("child1")) {
int value = Integer.parseInt(buf.toString().trim());
if (value <= 20) {
skipChildren = true;
}
...
} else if (qName.startsWith("child")) {
if (!skipChildren) {
int value = Integer.parseInt(buf.toString().trim());
doSomethingWith(value);
}
}
}
@Override
public void characters(char[] ch, int start, int length) {
if (!skipChildren) {
buf.append(ch, start, length);
}
}
答案 1 :(得分:0)
以下是使用vtd-xml执行任务的代码,它是xml处理技术的最新技术,并且比SAX更高效,更易于编写...关键是使用xpath表达式只过滤掉感兴趣的节点...读取this paper,它给你很多理由,以尽可能避免SAX解析
Processing XML with Java – A Performance Benchmark
import com.ximpleware.*;
public class conditionalSelection {
public static void main(String s[]) throws VTDException{
VTDGen vg = new VTDGen();
if(!vg.parseFile("d:\\xml\\condition.xml", false)) // disable namespace
return;
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("/root/parent[child1>20]"); // the xpath selecting all parents with child1>20
int i=0,j=0;
while((i=ap.evalXPath())!=-1){
// now move the cursor to child2 and child3
if(vn.toElement(VTDNav.FC,"child2")){
j = vn.getText();
if (j!=-1)//make sure the text node exist
System.out.println(" child2's text node is ==>"+ vn.toString(j));
vn.toElement(VTDNav.P);
}
if(vn.toElement(VTDNav.FC,"child3")){
j = vn.getText();
if (j!=-1)//make sure the text node exist
System.out.println(" child3's text node is ==>"+ vn.toString(j));
vn.toElement(VTDNav.P);
}
}
}