【问题标题】:XML SAXParser reformat if else Java/AndroidXML SAXParser 重新格式化 if else Java/Android
【发布时间】:2013-02-22 14:22:33
【问题描述】:

我有以下问题:

我正在使用 XML SAXParser 来解析 xml 文件并动态创建类并设置它们的属性。

我编写的代码现在可以创建 4 个类并设置类的属性,但问题是代码是一个很大的条件案例(if/else if/else)并且很难阅读。

我想解析xml,所以我可以创建15个不同的类,所以代码变得非常大。

现在确切的问题是如何将 if/elseif/else 重构为可读性更好的代码?我已经搜索了一段时间,发现了一些方法,例如使用地图或命令模式,但我不明白如何使用?

这是我目前正在使用的代码:

public class XmlParserSax extends DefaultHandler {

List<Fragment> fragments = null;
String atType = null;
String typeObject;
String currentelement = null;
String atColor = null;
RouteFragment route = null;
ChapterFragment chapter = null;
FirstFragment first = null;
ExecuteFragment execute = null;
StringBuilder textBuilder;

public XmlParserSax() {
    fragments = new ArrayList<Fragment>();
    try {
        /**
         * Create a new instance of the SAX parser
         **/
        SAXParserFactory saxPF = SAXParserFactory.newInstance();
        SAXParser sp = saxPF.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        /**
         * Create the Handler to handle each of the XML tags.
         **/

        String file = "assets/test.xml";
        InputStream in = this.getClass().getClassLoader()
                .getResourceAsStream(file);

        xr.setContentHandler(this);
        xr.parse(new InputSource(in));

    } catch (Exception e) {
        System.out.println(e);
    }
}

@Override
public void startElement(String uri, String localName, String qName,
        Attributes attributes) throws SAXException {

    atColor = attributes.getValue("color");
    atType = attributes.getValue("type");
    currentelement = localName;
    textBuilder = new StringBuilder();

    if (localName.equalsIgnoreCase("template")) {

        if (atType.equalsIgnoreCase("route")) {

            route = new RouteFragment();
            typeObject = "route";
        } else if (atType.equalsIgnoreCase("chapter")) {

            chapter = new ChapterFragment();
            typeObject = "chapter";
        } else if (atType.equalsIgnoreCase("first")) {
            first = new FirstFragment();
            typeObject = "first";
        } else if (atType.equalsIgnoreCase("execute")) {
            execute = new ExecuteFragment();
            typeObject = "execute";
        }
    } else if (localName.equalsIgnoreCase("number")) {
        if (typeObject.equalsIgnoreCase("chapter")) {
            chapter.setNumberTextcolor("#" + atColor);
        }
    } else if (localName.equalsIgnoreCase("maxnumber")) {
        if (typeObject.equalsIgnoreCase("chapter")) {
            chapter.setMaxNumberColor("#" + atColor);
        }

    } else if (localName.equalsIgnoreCase("title")) {
        if (typeObject.equalsIgnoreCase("chapter")) {
            chapter.setTitleColor("#" + atColor);
        } else if (typeObject.equalsIgnoreCase("first")) {
            first.setTitleColor("#" + atColor);
        }
    } else if (localName.equalsIgnoreCase("subtitle")) {
        if (typeObject.equalsIgnoreCase("first")) {
            first.setSubtitleColor("#" + atColor);
        }
    } else if (localName.equalsIgnoreCase("text")) {
        if (typeObject.equalsIgnoreCase("execute")) {
            execute.setTextColor("#" + atColor);
        }
    }

}

@Override
public void endElement(String uri, String localName, String qName)
        throws SAXException {

    String text = textBuilder.toString();
    if (localName.equalsIgnoreCase("template")) {
        if (typeObject.equalsIgnoreCase("route")) {
            fragments.add(route); // nieuw routefragment
                                    // toevoegen aan de lijst

        } else if (typeObject.equalsIgnoreCase("chapter")) {
            fragments.add(chapter); // nieuw chapterfragment
                                    // toevoegen aan de lijst

        } else if (typeObject.equalsIgnoreCase("first")) {
            fragments.add(first);
        } else if (typeObject.equalsIgnoreCase("execute")) {
            fragments.add(execute);
        }
    } else if (localName.equalsIgnoreCase("text")) {
        if (typeObject.equalsIgnoreCase("route")) {
            // route.setOmschrijving(text);
        } else if (typeObject.equalsIgnoreCase("execute")) {
            execute.setText(text);
        }
    } else if (localName.equalsIgnoreCase("background")) {
        if (typeObject.equalsIgnoreCase("route")) {
            // route.setKleur("#" + text);
        } else if (typeObject.equalsIgnoreCase("chapter")) {
            chapter.setBackgroundColor("#" + text);
        } else if (typeObject.equalsIgnoreCase("first")) {
            first.setBackgroundColor("#" + text);
        } else if (typeObject.equalsIgnoreCase("execute")) {
            execute.setBackgroundColor("#" + text);

        }
    } else if (localName.equalsIgnoreCase("number")) {
        if (typeObject.equalsIgnoreCase("chapter")) {
            chapter.setNumber(text);
        }
    } else if (localName.equalsIgnoreCase("maxnumber")) {
        if (typeObject.equalsIgnoreCase("chapter")) {
            chapter.setMaxNumber(text);
        }
    } else if (localName.equalsIgnoreCase("title")) {
        if (typeObject.equalsIgnoreCase("chapter")) {
            chapter.setTitle(text);
        } else if (typeObject.equalsIgnoreCase("first")) {
            first.setTitle(text);
        }
    } else if (localName.equalsIgnoreCase("subtitle")) {
        if (typeObject.equalsIgnoreCase("first")) {
            first.setSubtitle(text);
        }
    } else if (localName.equalsIgnoreCase("square")) {
        if (typeObject.equalsIgnoreCase("execute")) {
            execute.setBorderColor("#" + text);

        }
    }
}

public List<Fragment> getList() {
    return fragments;

}

@Override
public void characters(char[] ch, int start, int length)
        throws SAXException {

    textBuilder.append(ch, start, length);

}

}

【问题讨论】:

  • 我曾经回答过类似的问题,请查看:stackoverflow.com/questions/13417363/…
  • @Atrix1987 我不明白为什么你的版本代码更少?你还在用很多 if else 吗?
  • 还有另一种方法,使用开始元素和结束元素监听器,我会发布一些代码

标签: java android xml-parsing sax


【解决方案1】:

还有另一种方法可以做到这一点;使用 startElementListener 和 EndTextElementListeners

首先定义你的根元素:

    RootElement root = new RootElement("root");

定义你的子元素

    Element nodeA = root.getChild("nodeA");
    Element nodeB = root.getChild("nodeB");
    Element nodeC = root.getChild("nodeC");

现在设置监听器

    root.setStartElementListener(new StartElementListener() {
            public void start(Attributes attributes) {
                foundElement = true;// tells you that you are parsing the intended xml
            }
        });

    nodeA.setEndTextElementListener(new EndTextElementListener() {
            public void end(String body) {
                //populate your pojo
            }
        });

这样你可以取消所有那些 if-else 语句和布尔值,但你必须忍受 N 个监听器。

【讨论】:

  • 嗯,我会考虑到这一点,现在我正在尝试使用枚举,代码看起来更具可读性:)
猜你喜欢
  • 1970-01-01
  • 2019-12-15
  • 2019-04-01
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 2016-08-26
  • 2013-01-06
  • 2021-09-22
相关资源
最近更新 更多