1

我不知道为什么,但我很难理解 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();
        }
    }

抱歉发了这么长的帖子,感谢您的帮助!

4

2 回答 2

0

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

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

于 2013-09-13T05:07:23.737 回答
0

1 首先你正在阅读 xml 文件

2 调用 DOM 解析器,它从与您的 xml 对应的元素中创建内存结构

3 获取根元素

4 迭代根元素的子元素

就这样

于 2013-09-13T05:08:02.170 回答