在下面的用于处理xml元素的Java代码中,我使用了多个if-else条件。有什么更好的方法来避免这些if-else条件,其中我已使用“ A”和“ B”进行条件检查。

我的代码:

     ...
        if(((Element)nodeValue).hasAttribute("name")) {
            String nVal = ((Element)nodeValue).getAttribute("name");
            if(nVal.equals("A")) {
                rNodeContent = nodeValue.getTextContent();
                ... Processing...
            } else if(nVal.equals("B")) {
                rNodeContent = nodeValue.getTextContent();
                ... Processing...
            }
        }
     ...

最佳答案

在Java SE 7和更高版本中,您可以对多个switch值使用String语句,因为它可能更具可读性:

String nVal = ((Element)nodeValue).getAttribute("name");
switch(nVal){
    case "A":
       // processing
       break;
    case "B":
       // processing
       break;
    default:
       throw new IllegalArgumentException("Invalid nVal value: " +nVal);
}

关于java - 避免对Java Xml元素使用多个if-else,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44055900/

10-10 10:31