parsing Xml with NodeList and DocumentBuilder

前端 未结 1 656
夕颜
夕颜 2020-12-29 13:07

Having a bit of trouble parsing xml with dom and DocumentBuilder. I\'m able to get it working, but I guess I get a bit confused with all the child nodes, etc.

Here\

相关标签:
1条回答
  • 2020-12-29 13:31

    That should work as you described:

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    
    Document doc = builder.parse("input.xml");
    
    NodeList labTestList = doc.getElementsByTagName("LabTest");
    for (int i = 0; i < labTestList.getLength(); ++i)
    {
        Element labTest = (Element) labTestList.item(i);
        String labTestType = labTest.getAttribute("type");
    
        NodeList valueList = labTest.getElementsByTagName("value");
        for (int j = 0; j < valueList.getLength(); ++j)
        {
            Element value = (Element) valueList.item(j);
            String valueType = value.getAttribute("type");
    
            NodeList conditionList = value.getElementsByTagName("condition");
            for (int k = 0; k < conditionList.getLength(); ++k)
            {
                Element condition = (Element) conditionList.item(k);
                String conditionText = condition.getFirstChild().getNodeValue();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题