[英]How to read XML Property value using Java
我需要使用Java讀取XML數據。
這是我的XML文件片段。
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://192.168.1.55/tisas</property>
<property name="connection.username">root</property>
<property name="connection.password">xxyy</property>
<property name="show_sql">false</property>
我需要使用Java從xml文件中獲取值(jdbc:mysql://192.168.1.55/tisas)。 我怎么才能得到它?
有多種方法可以實現這一目標。 我假設您對於運行時間較長的應用程序閱讀了一次,因此性能不應該成為問題。 因此,我將選擇Java XPath API( Tutorial )。
這是一個使用XPath的完整示例(請注意:將StringReader
替換為任何適合您使用的Reader
,例如FileReader
):
import java.io.StringReader;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;
public class XPath {
public static void main(String[] args) throws Exception {
String xml = "<hibernate-configuration><session-factory><property name=\"hibernate.connection.provider_class\">org.hibernate.connection.C3P0ConnectionProvider</property><property name=\"connection.driver_class\">com.mysql.jdbc.Driver</property><property name=\"connection.url\">jdbc:mysql://192.168.1.55/tisas</property></session-factory></hibernate-configuration>";
String connectionUrl = XPathFactory.newInstance().newXPath().compile("//session-factory/property[@name='connection.url']/text()").evaluate(new InputSource(new StringReader(xml)));
System.out.println("connectionUrl = " + connectionUrl);
}
}
如果您只需要文件中的單個值,則不會使用DOM(如Ram所建議的),它將需要更多代碼。
假設有Hibernate庫可用,並且屬性文件存儲在config.xml中:
new Configuration().addFile("config.xml").getProperty("connection.url")
使用dom4j及其文檔中有許多示例說明了如何實現您的目標
這是使用Xerces庫的示例:
String xpath = "/hibernate-configuration/session-factory/property[@name='connection.url']/text()";
// Create the builder and parse the file
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
Document doc = factory.newDocumentBuilder().parse(new File("src/xml/input.xml"));
// Get the matching elements
String url = org.apache.xpath.XPathAPI.selectNodeList(doc, xpath).item(0).getNodeValue();
System.out.println(url);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.