我有一个从第 3 方源解码 xml 的类(我无法控制内容)。这是解码的片段:
JAXBContext jContext = JAXBContext.newInstance("com.optimumlightpath.it.aspenoss.xsd");
Unmarshaller unmarshaller = jContext.createUnmarshaller() ;
StringReader xmlStr = new StringReader(str.value);
Connections conns = (Connections) unmarshaller.unmarshal(xmlStr);
Connections
是使用 xjc 生成的类 dtd->xsd->class。 com.optimumlightpath.it.aspenoss.xsd
包包含所有此类类。
我收到的 xml 在 DOCTYPE 中包含一个相对路径。上面的 str.value
基本上包含:
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<!DOCTYPE Connections SYSTEM "./dtd/Connections.dtd">
<Connections>
...
</Connections>
这作为 java 1.5 应用程序成功运行。为了避免上述错误,我必须在项目根目录之外创建一个 ./dtd 目录并包含所有 dtd 文件(不知道为什么我必须这样做,但我们会解决的)。
我已经在 Tomcat5.5 上创建了一个使用上述类的 Web 服务。我得到 [org.xml.sax.SAXParseException: Relative URI "./dtd/Connections.dtd";没有文档 URI 无法解析。]
在解码行上。我尝试在每个相关文件夹(项目根目录、WebContent、WEB-INF、tomcat 工作目录等)中创建 ./dtd,但无济于事。
问题 #1:我在哪里可以找到 ./dtd 以便类在作为 tomcat web 服务运行时可以找到它?是否需要执行任何 tomcat 或服务配置才能识别目录?
问题 #2:为什么类首先需要 dtd 文件?难道它没有在 dtd->xsd->class 的注释中解码所需的所有信息吗?我读过很多关于禁用验证、设置 EntityResource 和其他解决方案的帖子,但是这个类并不总是部署为 Web 服务,我不想有两个代码序列。
最佳答案
从 InputStream 或 Reader 解码时,解析器不知道文档的 systemId(uri/位置),因此它无法解析相对路径。似乎解析器尝试使用当前工作目录解析引用,这仅在从 ide 或命令行运行时有效。如 Blaise Doughan 所述,为了覆盖此行为并自行解决问题,您需要实现 EntityResolver
。
经过一些试验后,我找到了执行此操作的标准方法。您需要从 SAXSource
中解码,后者又由 XMLReader
和 InputSource
构建。在此示例中,dtd 位于带注释的类旁边,因此可以在类路径中找到。
主.java
public class Main {
private static final String FEATURE_NAMESPACES = "http://xml.org/sax/features/namespaces";
private static final String FEATURE_NAMESPACE_PREFIXES = "http://xml.org/sax/features/namespace-prefixes";
public static void main(String[] args) throws JAXBException, IOException, SAXException {
JAXBContext ctx = JAXBContext.newInstance(Root.class);
Unmarshaller unmarshaller = ctx.createUnmarshaller();
XMLReader xmlreader = XMLReaderFactory.createXMLReader();
xmlreader.setFeature(FEATURE_NAMESPACES, true);
xmlreader.setFeature(FEATURE_NAMESPACE_PREFIXES, true);
xmlreader.setEntityResolver(new EntityResolver() {
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
// TODO: Check if systemId really references root.dtd
return new InputSource(Root.class.getResourceAsStream("root.dtd"));
}
});
String xml = "<!DOCTYPE root SYSTEM './root.dtd'><root><element>test</element></root>";
InputSource input = new InputSource(new StringReader(xml));
Source source = new SAXSource(xmlreader, input);
Root root = (Root)unmarshaller.unmarshal(source);
System.out.println(root.getElement());
}
}
根.java
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
@XmlElement
private String element;
public String getElement() {
return element;
}
public void setElement(String element) {
this.element = element;
}
}
root.dtd
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT root (element)>
<!ELEMENT element (#PCDATA)>
关于xml - 使用 DTD 的相对路径解码文档时出现 JAXB SAXParseException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3587196/