我试图使用SAX解析器动态地读取XML,我已经尝试过使用 这个 但在这个例子中,我必须为所有的子标签硬编码(创建一个变量),请建议在SAX中是否有任何可用的功能。
XML示例。
<cloudHubDeployment>
<uri>https://anypoint.mulesoft.com</uri>
<muleVersion>${muleVersion}</muleVersion>
<username>${username}</username>
<password>${password}</password>
<properties>
<env>${env}</env>
</properties>
</cloudHubDeployment>
我的要求是读取所有的子标签和它们的后续值在
尝试用下面的解决方案。
try {
File inputFile = new File("Input.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document document = dBuilder.parse(inputFile);
document.getDocumentElement().normalize();
Element rootElement = document.getDocumentElement(); // gets the document's root element (cloudHubDeployment)
NodeList nodeList = rootElement.getElementsByTagName("*"); // get all child elements under the root (cloudHubDeployment) element
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
System.out.println("Element Name : "+node.getNodeName()+", "
+ "Value : "+element.getTextContent().trim());
}
}
} catch (Exception e) {
e.printStackTrace();
}
输出。
Element Name : uri, Value : https://anypoint.mulesoft.com
Element Name : muleVersion, Value : ${muleVersion}
Element Name : username, Value : ${username}
Element Name : password, Value : ${password}
Element Name : properties, Value : ${env}
Element Name : env, Value : ${env}
收集xml文件中的所有元素和值。
NodeList nodeList = document.getElementsByTagName("*");
for (int temp = 0; temp < nodeList.getLength(); temp++) {
Node node = nodeList.item(temp);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
System.out.println("Element Name : "+node.getNodeName()+", "
+ "Value : "+element.getTextContent().trim());
}
}