想要使用DOM迭代XML中的层次结构

时间:2015-07-08 06:35:52

标签: java xml

我正在尝试迭代这个XML

<?xml version="1.0" encoding="utf-8"?>
<Document>
    <Sitemap>
        <TreeMap>
            <RootNodes>
                <TreeMapNode>
                    <NodeType>Folder</NodeType>
                    <NodeValue>fwreference_war</NodeValue><!--component name=project name-->
                    <ChildNodes>
                        <TreeMapNode>
                            <NodeType>Folder</NodeType>
                            <NodeValue>education</NodeValue><!--packegeName=nodevalue.title-->
                            <ChildNodes>
                                <TreeMapNode>
                                    <NodeType>Folder</NodeType>
                                    <NodeValue>editorsample::Mapping</NodeValue><!--title=mapping ; name=editorsample-->
                                    <ChildNodes>
                                        <TreeMapNode>
                                            <NodeType>PackageHandle</NodeType>
                                            <NodeValue>01::inquiry::list</NodeValue><!--sceenName::screenmode::screentype-->
                                            <ChildNodes />
                                        </TreeMapNode>
                                    </ChildNodes>
                                </TreeMapNode>
                            </ChildNodes>
                        </TreeMapNode>
                    </ChildNodes>
                </TreeMapNode>
            </RootNodes>
        </TreeMap>
    </Sitemap>
    <Mastermap>
        <TreeMap>
            <RootNodes />
        </TreeMap>
    </Mastermap>
    <Pages />
    <Masters />
</Document>

1)我想在<NodeType>内提取每个<sitemap>的值。

2)当我尝试从<sitenode>进行迭代但是当我尝试查找子节点时,结果如下:

 NodeList headerList = doc.getElementsByTagName("Sitemap");
    NodeList childNodeList=headerList.item(0).getChildNodes();
    //gives 3
    NodeList headerList = doc.getElementsByTagName("TreeMap");
    NodeList childNodeList=headerList.item(0).getChildNodes();
    //gives 3
    NodeList headerList = doc.getElementsByTagName("RootNodes");
    NodeList childNodeList=headerList.item(0).getChildNodes();
    //gives 3
    NodeList headerList = doc.getElementsByTagName("TreeMapNode");
    NodeList childNodeList=headerList.item(0).getChildNodes();
    //gives 8

如何迭代这个层次结构以及为什么上面三个标签给出相同的no。儿童节点,即3?

1 个答案:

答案 0 :(得分:1)

你即将解决它。您可以遍历子项并检查它是否为Node.ELEMENT_NODE

你的元素有3个孩子的原因是因为它有混合的内容。标签前面有一些空格和一个新行。所以基本上每个节点都有[Node.TEXT_NODE, NODE.ELEMENT_NODE, Node.TEXT_NODE]

的列表