Java:无法理解XML DOM Parser Code

时间:2013-09-13 05:00:05

标签: java xml parsing dom

我不知道为什么,但是我很难理解XML DOM Parsing,并且想知道是否有人可以帮助我理解代码。目前,我有以下XML文件内容:

<environment>
  <gravity direction="90" magnitude="20"/>
  <viscosity magnitude="0.8"/>
  <centermass magnitude="100" exponent="2.0"/>
  <wall id="1" magnitude="40" exponent="1.5"/>
  <wall id="2" magnitude="50" exponent="2.0"/>
  <wall id="3" magnitude="180" exponent="1.0"/>
  <wall id="4" magnitude="10" exponent="0.0"/>
</environment>

这是我从不同教程编译的Java类,但是当我尝试从各个节点中提取重力,粘度等值时,我会陷入困境。

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.*;

public class XMLParser{

    public static void main(String[] args) {
        try {

            File environment = new File("environment.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(environment);
            doc.getDocumentElement().normalize();

            System.out.println("Root element: " + doc.getDocumentElement().getNodeName());

            NodeList nodes = doc.getElementsByTagName("environment");

            for (int i = 0; i < nodes.getLength(); i++) {
                Node node = nodes.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;

// I don't think I need to loop through nodes because I only have one environment node, but I've kept it there to deal with general cases. Then node contains the child nodes I would like to extract data from, such as gravity, viscosity, etc, but I'm not sure quite how to do it. 
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

很抱歉这篇帖子很长,谢谢你的帮忙!

2 个答案:

答案 0 :(得分:0)

因此,您将在循环中查看的一个节点将成为根元素节点。遍历其子节点,它们将是您感兴趣的实际节点。您可以像访问根元素一样执行此操作。此外,您可以轻松地谷歌上这个教程:

http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/

答案 1 :(得分:0)

1首先,您正在阅读xml文件

2调用DOM解析器,该解析器在与您的xml相对应的Elements的memmory结构中创建

3获取根元素

4迭代根元素的孩子

多数人