Java XML读取问题:读取不同的子标记

时间:2011-05-26 05:28:30

标签: java xml

有人可以告诉我如何阅读这种XML文件来获取子元素名称吗?

 <CEB>
    <MOREVALUES></MOREVALUES>
 </CEB>

 <DILOG>
    <MOREVALUES></MOREVALUES>
 </DILOG>

 <MOBITLE>
    <MOREVALUES></MOREVALUES>
 </MOBITLE>     

例如,我想阅读<CTLBILL>标记内的所有子标记。在这种情况下,<CEB><DILOG><MOBITLE>

这不起作用:

public static void getTags() {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new File("C:\\ctlbill.xml"));
            NodeList nodeLst = doc.getChildNodes();
            for (int s = 0; s < nodeLst.getLength(); s++)
            {           
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
}

1 个答案:

答案 0 :(得分:1)

尝试使用:

NodeList nodeLst = doc.getDocumentElement().getChildNodes();
for (int s = 0; s < nodeLst.getLength(); s++)
    if (nodeLst.item(s) instanceof Element)
        System.out.println(nodeLst.item(s).getNodeName());

我假设CTLBILL是包含CEB,DILOG和MOBITLE元素的文档(根)元素(格式良好的XML必须只有一个根元素)。

相关问题