当我在元素节点上时,如何简化乱七八糟的代码?我的代码如下所示:
private void readXmldata(String xml_debug_settings)
{
File xml_debug_settings_file = new File(xml_debug_settings);
if (xml_debug_settings_file.exists())
{
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read(xml_debug_settings_file);
Element root = document.getRootElement();
Iterator itr = root.elements().iterator();
Element element =null;
while (itr.hasNext()) {
Element debel = (Element) itr.next();
if (debel.getName().equals("mainnode")) {
Iterator itrd = debel.elementIterator();
while (itrd.hasNext())
{
Element child = (Element) itrd.next();
System.out.println(child.getName());
if (child.getName().equals("node1"))
{
System.out.println(child.getText());
}
if (child.getName().equals("node2"))
{
System.out.println(child.getText());
}
if (child.getName().equals("node3"))
{
System.out.println(child.getText());
}
if (child.getName().equals("node4"))
{
System.out.println(child.getText());
}
if (child.getName().equals("node4"))
{
System.out.println(child.getText());
}
if (child.getName().equals("node5"))
{
System.out.println(child.getText());
}
}
}
}
} catch (DocumentException ex) {
Logger.getLogger(Debugsettings.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
我想要这个例子的代码更少:(非常混乱并且没有正确清理代码):
if (child.getName().equals("node1"))
{
System.out.println(child.getText());
}
if (child.getName().equals("node2"))
{
System.out.println(child.getText());
}
if (child.getName().equals("node3"))
{
System.out.println(child.getText());
}
if (child.getName().equals("node4"))
{
System.out.println(child.getText());
}
if (child.getName().equals("node4"))
{
System.out.println(child.getText());
}
if (child.getName().equals("node5"))
{
System.out.println(child.getText());
}