2016-04-29 114 views
3
<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> 

跳過父標籤,基於XML解析的子標籤的價值,我真正的新編碼的世界,SAX解析.. 考慮以上XML,我需要的是。 ..基於標籤child1的值,如果它大於20,那麼我只想解析剩餘的子標籤(child2和child3),否則我會想要移到下一個父標籤。如何使用SAX解析器

任何人都可以請建議什麼是最理想的方式來做到這一點?

+0

爲什麼選擇薩克斯?它是否適合龐大的XML? –

+0

是的,它是巨大的XML,也是一個已經存在的代碼,我試圖做一些修改。 –

+0

有多大?百萬分之幾MB還是100百萬分之一? –

回答

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); 
    } 
} 
+0

謝謝@Maurice Perry。看起來這會工作。 –

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); 
      } 
     } 
    }