0
由於某種原因,我希望能夠讀取我的hibernate配置文件中的屬性,比如說我需要知道使用什麼方言或什麼數據庫驅動類。我試圖通過解析XML要做到這一點,但我沒有得到過的屬性:閱讀休眠配置文件中的屬性
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
/**
*
* @author User
*/
public class XmlParser {
public XmlParser() {
}
public void readXml() throws SAXException, IOException, ParserConfigurationException {
InputStream in = this.getClass().getResourceAsStream("/hibernate.cfg.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(in);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("property");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Driver : " + eElement.getAttribute("name"));
System.out.println("Not Sure : " + eElement.getElementsByTagName("hibernate.connection.url").item(0).getTextContent());
System.out.println(eElement.getElementsByTagNameNS("name", "hibernate.dialect").item(0).getTextContent());
}
}
}
}
我的輸出是:
Root element :hibernate-configuration
----------------------------
Current Element :property
Driver : hibernate.dialect
null
我需要能夠獲得的屬性值的任何時間我的應用程序。在這種方法中有沒有另一種方法或缺少什麼?
@Stanley不回答可以幫助你 – 2014-09-01 06:14:46