我正在解析(大量的)XML文件,其中包含我事先不知道的实体引用(无法更改这个事实)。
例如:
xml = "<tag>I'm content with &funny; &entity; &references;.</tag>"
当我尝试使用以下代码解析它时:
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
final DocumentBuilder db = dbf.newDocumentBuilder();
final InputSource is = new InputSource(new StringReader(xml));
final Document d = db.parse(is);
我遇到了以下异常:
org.xml.sax.SAXParseException: The entity "funny" was referenced, but not declared.
但是,我想要实现的是,解析器将每个未声明的实体(解析器不知道的实体)替换为空字符串''。甚至更好的方法是,是否有一种方法可以向解析器传递地图,例如:
Map<String,String> entityMapping = ...
entityMapping.put("funny","very");
entityMapping.put("entity","important");
entityMapping.put("references","stuff");
这样我就可以做以下事情:
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
final DocumentBuilder db = dbf.newDocumentBuilder();
final InputSource is = new InputSource(new StringReader(xml));
db.setEntityResolver(entityMapping);
final Document d = db.parse(is);
如果我使用这个示例代码从文档中获取文本,我应该会得到:
I'm content with very important stuff.
有什么建议吗?当然,我已经很高兴只用空字符串替换未知实体了。
谢谢。
...Resolver
(解析器)类。这个类将负责解析这些引用。这就是.NET模型的工作方式。我认为这些概念在很大程度上是相同的。 - Marvin SmitEntityResolver
用于解析 外部 实体(例如 DTD),但我们正在寻找处理 内部 实体的东西。 - skaffman