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

问题描述 投票:0回答:1

我试图使用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>

我的要求是读取所有的子标签和它们的后续值在

java xml xml-parsing sax saxparser
1个回答
1
投票

尝试用下面的解决方案。

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());
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.