0

複数のレベルで同じタグ名を持つ xml を解析するためのソリューションを探していました。これは、私が取り組まなければならないことの XML サンプルです (セクションは静的ではありません)。

<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 で行ったことはまだ正しいものを生み出していません。言い換えれば、私は立ち往生しています:(

Section というクラスを作成しました。

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

親変数も追加する必要があるかどうか疑問に思っていますか?

public Section parent;

誰かが解決策を持っているなら、どうもありがとう!:D

4

1 に答える 1

1

実際、これには少なくともスタックが必要になる可能性があります。

クラス(セッター/ゲッターとセクションを追加するメソッド)に明確な変更を加えると(私は願っていますSection)、このハンドラーはトリックを行うようです:

レイアウトではルート<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;
    }
}
于 2013-03-17T20:40:07.600 に答える