我寫了類來解析一些xml到一個對象中,並且它不能正常工作,當我嘗試獲取節點的值時,我得到的是空值而不是節點的內容。爲什麼這個java代碼不能正確解析我的xml?
這裏是我班的一個簡化版本,只是做一個單一節點的XML解析:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XmlReaderCutDown {
private static Logger logger = Logger.getLogger(CtiButtonsXmlReader.class);
public static void testXml(String confFile){
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File(confFile));
doc.getDocumentElement().normalize();
if (logger.isDebugEnabled()){
logger.debug("The root element is " + doc.getDocumentElement().getNodeName());
}
NodeList rows = doc.getElementsByTagName("row");
NodeList topRowButtons = ((Element)rows.item(0)).getElementsByTagName("button");
logger.debug("Top row has " +topRowButtons.getLength() + " items.");
Node buttonNode = topRowButtons.item(0);
NodeList nodeList = ((Element)buttonNode).getElementsByTagName("id");
logger.debug("Node list count for "+ "id" + " = " + nodeList.getLength());
Element element = (Element)nodeList.item(0);
String xx = element.getNodeValue();
logger.debug(xx);
String elementValue = ((Node)element).getNodeValue();
if (elementValue != null) {
elementValue = elementValue.trim();
}
else {
logger.debug("Value was null");
}
logger.debug("Node id = "+ elementValue);
} catch (ParserConfigurationException e) {
logger.fatal(e.toString(),e);
} catch (SAXException e) {
logger.fatal(e.toString(),e);
} catch (IOException e) {
logger.fatal(e.toString(),e);
} catch (Exception e) {
logger.fatal(e.toString(),e);
}
}
public static void main(String[] args){
DOMConfigurator.configure("log4j.xml");
testXml("test.xml");
}
}
這裏是我的xml文件的一個精簡版:
<?xml version="1.0"?>
<root>
<row>
<button>
<id>this is an id</id>
<action>action</action>
<image-src>../images/img.png</image-src>
<alt-text>alt txt</alt-text>
<tool-tip>Tool tip</tool-tip>
</button>
</row>
</root>
這是日誌記錄輸出的內容:
DEBUG XmlReaderCutDown - 根元素是根
DEBUG XmlReaderCutDown - 頂行有1個項目。
DEBUG XmlReaderCutDown - 爲ID = 1
DEBUG節點列表計數XmlReaderCutDown -
DEBUG XmlReaderCutDown - 值爲空
DEBUG XmlReaderCutDown - 節點ID = NULL
爲什麼不它獲取XML節點中的文本?
我使用JDK 1.6_10
注意,如果你想嘗試一下,但不要有log4j的,那麼你可以替換系統日誌statments .out.println(); – 2009-06-10 10:23:17