使用java从复杂的xml中读取值

时间:2013-11-22 06:12:26

标签: java xml

我是Java新手并尝试读取XML文件。 这是我的XML文件: -

  <?xml version="1.0" encoding="UTF-8"?>
    <parameter>
<attribute>a</attribute>

这是我的代码我试图从xml读取密钥和值但我被卡住了。这是我的代码: -

public class TestDBMain {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        File file = new File("ACL.xml");
        DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = dbfactory.newDocumentBuilder();
        Document doc = builder.parse(file);
        NodeList nList = doc.getElementsByTagName("testCaseDataName");
        for(int i = 0;i<nList.getLength();i++){
            Node nNode = nList.item(i);
            if(nNode.getNodeType()== Node.ELEMENT_NODE){
                Element ele = (Element) nNode;
            //  System.out.println(ele.getTextContent());
                //System.out.println(ele.getElementsByTagName("testCaseName").item(0).getTextContent());
                System.out.println(ele.getAttributeNode("testCaseDataName"));
//I dont know which methods to use to print the key and value in the xml under parameter


            }
        }
    }
}

任何人都可以帮助我这个

2 个答案:

答案 0 :(得分:1)

您的代码读取<testCaseDataName>节点。它不会进入这个标签。 试试这个..

 for(int i = 0;i<nList.getLength();i++){
        NodeList nodeList = nList.item(i).getChildNodes();
        for(int j = 0;j<nList.getLength();j++){
            Node nNode = nodeList.item(j);
            if(nNode.getNodeType()== Node.ELEMENT_NODE){
                System.out.println(nNode.getNodeName() +" : "+nNode.getTextContent());
                if(nNode.getNodeName().equals("parameter")){
                    NodeList param = nNode.getChildNodes();
                    System.out.println("      "+param.item(0).getNodeName() +" : "+param.item(0).getTextContent());
                    System.out.println("      "+param.item(1).getNodeName() +" : "+param.item(1).getTextContent());
                }
            }
        }
    }  

答案 1 :(得分:1)

免责声明:我维护JDOM project,所以我有偏见....但是......这是JDOM的理想用例:

    Document doc = new SAXBuilder().build(new File("ACL.xml"));
    Element root = doc.getRootElement();
    for (Element testcase : root.getChildren()) {
        int id = Integer.parseInt(testcase.getChildText("id"));
        String name = testcase.getChildText("testCaseName");
        String expect = testcase.getChildText("expectedResult");
        Map<String,String> params = new LinkedHashMap<String,String>();
        Element parmemt = testcase.getChild("parameter");
        if (parmemt != null) {
            Iterator<Element> it = parmemt.getChildren().iterator();
            while (it.hasNext()) {
                Element key = it.next();
                if (!"key".equals(key.getName())) {
                    throw new IllegalStateException("Expected key but got " + key);
                }
                if (!it.hasNext()) {
                    throw new IllegalStateException("Expected value for key " + key);
                }
                Element val = it.next();
                if (!"value".equals(val.getName())) {
                    throw new IllegalStateException("Expected value but got " + val);
                }
                params.put(key.getValue(), val.getValue());
            }
        }
        System.out.printf("Processing test case %d -> %s\n    Expect %s\n    Parameters: %s\n",
             id, name, expect, params.toString());
    }

对我来说,这会产生输出

Processing test case 1 -> EditTest
    Expect nooptionsacltrue
    Parameters: {}
Processing test case 2 -> AddTest
    Expect featuresaddedacltrue
    Parameters: {featues=w,f}
Processing test case 3 -> AddTest
    Expect duplicateacltrue
    Parameters: {projectType=NEW, Name=28HPM, status=ACTIVE, canOrder=Yes}