从XML文件获取标记和值

时间:2013-10-31 12:40:09

标签: java xml xml-parsing

我有一个xml配置文件:

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Config>
    <useProxy>true</useProxy>
    <proxyReqPass>true</proxyReqPass>
    <proxyHost>proxy.net.br</proxyHost>
    <proxyUser>admin</proxyUser>
    <proxyPass>12345</proxyPass>
</Config>

我有一个Data()对象列表,每个Data()包含2个字符串,标签名称和标签值。所以我想在这个列表中插入这个xml文件的数据,例如:

List<Data> data = new ArrayList<Data>();

        File fXmlFile = new File("Config.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);

        doc.getDocumentElement().normalize();

        NodeList elements = doc.getElementsByTagName("Config");

        for (int i = 0; i < elements.getLength(); i++) {

            Node nNode = elements.item(i);

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;

                data.add(new Data(eElement.getTagName(), eElement.getTextContent()));

            }
        }

如果我打印清单:

for(int i = 0; i < list.size(); i++)
                System.out.println("Node: " + list.get(i).getTagName() + " Value: " + list.get(i).getTextContent());

我希望结果是:

> Node: useProxy Value: true
Node: proxyReqPass Value: true
Node: proxyHost Value: proxy.net.br
Node: proxyUser Value: admin
Node: proxyPass Value: 12345

但结果是:

> Node: Config Value: 
    false
    false

我不知道我的错误在哪里,请有人帮助我

1 个答案:

答案 0 :(得分:1)

您正在迭代搜索<Config>标记的结果。您应该迭代搜索结果子项。

NodeList configTags = doc.getElementsByTagName("Config");
// assuming there will only be one `Config` node
NodeList elements = configTags.item(0).getChildNodes();

for (int i = 0; i < elements.getLength(); i++) {
   // (everything else looks correct)...
}

当您查询getElementsByTagName()时,将返回一个NodeList,在您的情况下应始终包含一个节点<Config>节点。要访问子节点(<useProxy>等),您需要从节点列表中获取第一个节点并查询其子节点getChildNodes()