gpt4 book ai didi

java - 使用 SAX 解析器动态读取标签

转载 作者:行者123 更新时间:2023-12-02 08:39:57 30 4
gpt4 key购买 nike

我正在尝试使用 SAX 解析器动态读取 XML,我尝试过使用 this但在这个示例中,我必须为所有子标签进行硬编码(创建变量),请建议 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());
}
}

关于java - 使用 SAX 解析器动态读取标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61440982/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com