我有一个xml文件:
deltaQuery="select Uid from User where lastmodify > '${dataimporter.last_index_time}'">
该xml文件没有<?xml...>等标签
我想读取出dataSource标签中driver url等值,写了一个类如下:
File file = new File("data_config.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder=dbf.newDocumentBuilder();
Document doc=builder.parse(file);
NodeList dataSource = doc.getElementsByTagName("dataSource");
System.out.println(dataSource.getLength());
for(int i=0;i<dataSource.getLength();i++)
{
Node node=dataSource.item(i);
System.out.println(node);
System.out.println(node.getNodeValue());
}
总是说读到的null。
求大牛指正。
另外:我想读取所有filed下的column 和name标签的值,该怎么写呢?
File file = new File("data_config.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder=dbf.newDocumentBuilder();
Document doc=builder.parse(file);
[color=red]//获取文档的根元素,赋值给rootElement变量
Element rootElement = document.getDocumentElement();
NodeList dataSource = rootElement.getElementsByTagName("dataSource"); [/color]
System.out.println(dataSource.getLength());
for(int i=0;i<dataSource.getLength();i++)
{
Node node=dataSource.item(i);
System.out.println(node);
System.out.println(node.getNodeValue());
}
[code="java"]public class Test {
/**
* @param args
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*/
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {
// TODO Auto-generated method stub
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbf.newDocumentBuilder();
File file = new File("c:\\c.xml");
Document doc = builder.parse(file);
NodeList dataSource = doc.getElementsByTagName("dataSource");
for (int i = 0; i < dataSource.getLength(); i++) {
Node node = dataSource.item(i);
Element element = (Element) node;
System.out.println(element.getAttribute("url"));
}
NodeList field = doc.getElementsByTagName("field");
for (int i = 0; i < field.getLength(); i++) {
Node node = field.item(i);
Element element = (Element) node;
System.out.println(element.getAttribute("column"));
System.out.println(element.getAttribute("name"));
}
}
}[/code]
应该像1楼那样获得root节点,然后访问数据,还有提醒楼主注意文件路径应该写正确