2013-03-14 45 views
0

我一直在尋找一個解決方案,以解析我的XML在幾個級別上具有相同的標記名稱。這裏是什麼,我必須工作在一個XML樣本(的部分是不是靜態):Android SAX解析器 - 幾個級別上的相同標記名稱

<xml> 
    <section id="0"> 
    <title>foo</title> 
    <section id="1"> 
     <title>sub foo #1</title> 
     <section id="2"> 
      <title>sub sub foo</title> 
     </section> 
    </section> 
    <section id="3"> 
     <title>sub foo #2</title> 
    </section> 
    </section> 
<xml> 

我一直在嘗試了幾種可能性,比如試圖列表,堆棧,但我已經用SAX做不是招」沒有產生任何正確的東西;換句話說,我堅持:(

我創建了一個類調用部分:

public class Section { 
public String id; 
public String title; 
public List<Section> sections; } 

我想知道如果我還應該添加一個父變量

public Section parent; 

如果任何人有一個解決方案,我非常感謝你!:D

+0

您對xml的生成有任何影響嗎?我的猜測是SAX解析器試圖做父/子邏輯,並且由於所有命名都是「節」,因此無法正確構建節點之間的關係。 – JakeWilson801 2013-03-14 17:33:02

+0

不幸的是我沒有。是的,SAX解析器實際上會在每個節節點之後覆蓋我的節對象。我已經想過使用布爾變量在父節節點中將其設置爲true,但是一旦解析器進入下一節節點,布爾變量就沒有用處。但是,我使用了我使用的解析器,所以如果您知道一個可以解決此問題的好解析器,我一定會接受它! – Tomap 2013-03-15 08:17:30

回答

1

事實上,你可能至少需要一個這樣的堆棧

有了(我希望)明確更改您Section類(setter方法/ getter和添加一個節的方法),該處理器似乎這樣的伎倆:

由於您的佈局看起來馬上<section>標籤允許多個以下<xml>根,我已經實現它也把結果放入List<Section>

import org.xml.sax.Attributes; 
import org.xml.sax.SAXException; 
import org.xml.sax.helpers.DefaultHandler; 

import java.util.ArrayList; 
import java.util.List; 
import java.util.Stack; 

public class SectionXmlHandler extends DefaultHandler { 

    private List<Section> results; 
    private Stack<Section> stack; 
    private StringBuffer buffer = new StringBuffer(); 

    @Override 
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { 
     if ("xml".equals(localName)) { 
      results = new ArrayList<Section>(); 
      stack = new Stack<Section>(); 
     } else if ("section".equals(localName)) { 
      Section currentSection = new Section(); 
      currentSection.setId(attributes.getValue("id")); 
      stack.push(currentSection); 
     } else if ("title".equals(localName)) { 
      buffer.setLength(0); 
     } 
    } 

    @Override 
    public void endElement(String uri, String localName, String qName) throws SAXException { 
     if ("section".equals(localName)) { 
      Section currentSection = stack.pop(); 
      if (stack.isEmpty()) { 
       results.add(currentSection); 
      } else { 
       Section parent = stack.peek(); 
       parent.addSection(currentSection); 
      } 
     } else if ("title".equals(localName)) { 
      Section currentSection = stack.peek(); 
      currentSection.setTitle(buffer.toString()); 
     } 
    } 

    @Override 
    public void characters(char[] ch, int start, int length) throws SAXException { 
     buffer.append(ch, start, length); 
    } 

    public List<Section> getResults() { 
     return results; 
    } 
} 
+0

謝謝唐!這像一個魅力。 :) 我需要閱讀Stacks的文檔才能完全理解它,但是從您提交的內容來看,這對我來說似乎更加清晰! 至於部分課程,我的確寫過getters/setters。 – Tomap 2013-03-18 12:16:46