我不知道为什么,但我很难理解 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();
}
}
抱歉发了这么长的帖子,感谢您的帮助!