2. Write a console application which load a XML file defined
below and write a text file as described above.Typical usage : java -jar xml2calc.jar input.xml output.txtXML Format :<calc>
<op type=”TYPE”>
<first>
<op>...</op>
</first>
<second>
...
</second>
</op>
</calc><first>number | op</first>
<first value=”number”/>Operation types : ”add” | “sub” | “mul” | “div”Sample XML file :<?xml version="1.0"?>
<calc>
<op type=”add”>
<first>
<op type=”div”>
<first>
<op type=”mul”>
<first value=”3”/>
<second value=”2”/>
</op>
</first>
<second value=”5”/>
</op>
</first>
<second value=”2”/>
</op>
</calc>Sample output file :
3 * 2 / 5 + 2

解决方案 »

  1.   

    public class Operate { public static void main(String[] args) throws Exception{
    Operate op = new Operate();

    Document doc = read("06.xml");
    List listOP = doc.selectNodes("//op");
    Element eleOP = (Element)listOP.get(0);
    String result = op.makeExp(eleOP);

    Conica.pl(result);
    }

    public String makeExp(Element eleOP){
    String type = eleOP.attributeValue("type");
    List list = eleOP.elements();
    Element value;
    value = (Element)list.get(0);
    String first;
    List listFirst = value.elements();
    if(listFirst.size()> 0){
    Element eleFirst = (Element)listFirst.get(0);
    first = makeExp(eleFirst);
    }else{
    first = value.attributeValue("value");
    }
    value = (Element)list.get(1);
    String second = value.attributeValue("value");
    if(type.equals("add")){
    type = "+";
    } else if(type.equals("sub")){
    type = "-";
    } else if(type.equals("mul")){
    type = "*";
    } else if(type.equals("div")){
    type = "/";
    }
    return first + type + second;
    }

    public static Document read(String fileName) throws FileNotFoundException,DocumentException{
    SAXReader sax = new SAXReader();
    Document doc = sax.read(new File(fileName));
    return doc;
    }
    }0601.xml:<?xml version="1.0"?>
    <calc>
    <op type="add">
    <first>
    <op type="div">
    <first>
    <op type="mul">
    <first value="3"/>
    <second value="2"/>
    </op>
    </first>
    <second value="5"/>
    </op>
    </first>
    <second value="2"/>
    </op>
    </calc>