关于getChildNodes()的疑惑

J2EE 码拜 8年前 (2016-03-15) 1358次浏览
appconfig.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE app-config SYSTEM "appconfig.dtd">
<app-config>
	<package>com.framework.test</package>
	<suffix>Action</suffix>
	<parameter>a</parameter>
	<alials></alials>
	<pagesize></pagesize>
	<pagefull></pagefull>
	<ddlauto></ddlauto>
	<driver>com.mysql.jdbc.Driver</driver>
	<url>jdbc:mysql://localhost:3306/test</url>
	<user>root</user>
	<password>123456</password>
</app-config>

然后用DOC来解析这个xml文件:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ContextConfig {
	public static String pagefull = "none";
	public static String packages = "";
	public static String suffix = "";
	public static String redirect = "";
	public static String parameter = "a";
	public static String ddlauto = "none";
	public static String alials = "";
	public static String connType = "xml";
	public static String xmlPath = "";
	public static int pagesize = 0;


	public static void parserXml(String fileName) {
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document document = db.parse(fileName);
			NodeList conns = document.getChildNodes()
//System.out.println(conns.getLength());  --1--
			for (int i = 0; i < conns.getLength(); i++) {
				Node conn = conns.item(i);
//System.out.println(conn.getNodeName()+","+conn.getNodeValue()); --2--
				NodeList connInfo = conn.getChildNodes();
				for (int j = 0; j < connInfo.getLength(); j++) {
					Node node = connInfo.item(j);
					NodeList connMeta = node.getChildNodes();
					for (int k = 0; k < connMeta.getLength(); k++) {
						if (node.getNodeName().equals("suffix")) {
							suffix = connMeta.item(k).getTextContent();
						}
						if (node.getNodeName().equals("parameter")) {
							parameter = connMeta.item(k).getTextContent();
						}
						if (node.getNodeName().equals("ddlauto")) {
							ddlauto = connMeta.item(k).getTextContent();
						}
						if (node.getNodeName().equals("alials")) {
							alials = connMeta.item(k).getTextContent();
						}
						if (node.getNodeName().equals("package")) {
							packages = connMeta.item(k).getTextContent();
						}
						if (node.getNodeName().equals("pagesize")) {
							pagesize = Integer.parseInt(connMeta.item(k).getTextContent());
						}
						if (node.getNodeName().equals("pagefull")) {
							pagefull =connMeta.item(k).getTextContent();
						}
					}
				}
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}

问题1、在第1处的输出为什么是2,在xml里面不是只有一个app-config元素吗?
问题2、在第2处的输出为什么是:

app-config,null
app-config,null
解决方案

40

空行算一个。

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明关于getChildNodes()的疑惑
喜欢 (0)
[1034331897@qq.com]
分享 (0)