实现说明
用 DocumentBuilder 解析 XML可以归结为类 XmlConfigReader。
for (int i = 0; i < services.getLength(); i++) 承担全部的逐项处理。
使用要点
org.w3c.dom.Document、org.w3c.dom.Element、org.w3c.dom.NodeList必须先装好——示例直接导入它们。- 跑完文件,输出里会留下标记——
root:。
常见问题
要先安装哪些包?
需要。导入解析到 org.w3c.dom.Document、org.w3c.dom.Element、org.w3c.dom.NodeList,由包管理器提供。
核心语句
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
代码示例
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class XmlConfigReader {
public static void main(String[] args) throws Exception {
String xml = """
<deploy>
<service name="api" replicas="3" />
<service name="worker" replicas="2" />
</deploy>""";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// 加固:禁用 DOCTYPE 声明,堵住 XXE 外部实体注入
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
Document doc = factory.newDocumentBuilder()
.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
NodeList services = doc.getElementsByTagName("service");
for (int i = 0; i < services.getLength(); i++) {
Element service = (Element) services.item(i);
System.out.println(service.getAttribute("name")
+ " replicas=" + service.getAttribute("replicas"));
}
System.out.println("root: " + doc.getDocumentElement().getTagName());
}
}