Java中将XML转为Document需用JAXP的DocumentBuilder,关键在于配置DocumentBuilderFactory防御XXE:禁用DOCTYPE声明、外部实体和参数实体,并根据字符串或文件选择InputSource或File作为输入源。

Java中将XML字符串或文件转换为 org.w3c.dom.Document 对象,核心是使用JAXP(Java API for XML Processing)提供的 DocumentBuilder。关键在于正确配置 DocumentBuilderFactory,避免默认不安全的解析行为(如XXE漏洞),并处理好输入源。
从XML字符串解析为Document
适用于已知XML内容为字符串(如HTTP响应体、配置片段)的场景。需将字符串转为 InputStream 或 InputSource:
- 用
StringReader包装字符串,再构造InputSource - 禁用外部DTD和实体解析,防止XXE攻击(必须设置)
- 推荐使用
DocumentBuilderFactory.newInstance().setFeature(...)显式关闭危险特性
String xml = "<root><name>Alice</name></root>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// 关键:防御XXE
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml)));
登录后复制
从XML文件解析为Document
适用于读取本地或类路径下的XML文件。输入源为 File 或 InputStream(如 getClass().getResourceAsStream()):
- 若文件路径来自用户输入,务必校验路径合法性,避免目录遍历
- 仍需保持上述安全特性设置,不可省略
- 使用
builder.parse(new File("config.xml"))最简洁;若用流,注意编码(建议显式指定UTF-8)
InputStream is = getClass().getResourceAsStream("/data/sample.xml");
Document doc = builder.parse(is); // is会自动关闭(JDK7+)
登录后复制
常见问题与注意事项
实际使用中容易忽略但影响稳定性和安全性的细节:
标签: java html js apache 编码 win stream 常见问题 java api 字符串解析
还木有评论哦,快来抢沙发吧~