問題描述
我想解析以下 XML 文檔以解析其中的所有實體:
<!DOCTYPE doc SYSTEM 'mydoc.dtd'><doc>&title;</doc>
我的 EntityResolver 應該從數(shù)據(jù)庫中獲取具有給定系統(tǒng) ID 的外部實體,然后進行解析,請參見下圖:
私有靜態(tài)類 MyEntityResolver{public InputSource resolveEntity(String publicId, String systemId)拋出 SAXException、IOException{//此時systemId總是被絕對化為當前工作目錄,//即使 XML 文檔將其指定為相對的.//例如file:///H:/mydoc.dtd" 而不僅僅是mydoc.dtd"http://為什么???我怎樣才能防止這種情況???SgmlEntity 實體 = findEntityFromDatabase(systemId);InputSource is = new InputSource(new ByteArrayInputStream(entity.getContents()));is.setPublicId(publicId);is.setSystemId(systemId);回報是;}}
我嘗試使用 DOM (DocumentBuilder) 和 SAX (XMLReader),將實體解析器設置為 MyEntityResolver(即 setEntityResolver(new MyEntityResolver())
),但 systemId
在 MyEntityResolver#resolveEntity(String publicId, String systemId)
中總是被絕對化到當前工作目錄.
我也嘗試調(diào)用 setFeature("http://xml.org/sax/features/resolve-dtd-uris", false);
,但沒有任何幫助.p>
那么我怎樣才能實現(xiàn)我想要的呢?
謝謝!
顯然還有一個接口叫EntityResolver2 是舊 EntityResolver.(談論令人困惑的名字!)
無論如何,我發(fā)現(xiàn) EntityResolver2
實現(xiàn)了我想要的,也就是說,它沒有對 systemId
進行任何更改,所以它始終是指定的在 XML 文檔中.
I want to parse the following XML document to resolve all entities in it:
<!DOCTYPE doc SYSTEM 'mydoc.dtd'>
<doc>&title;</doc>
My EntityResolver is supposed to fetch the external entity with the given system ID from the database and then do the resolution, see below for an illustration:
private static class MyEntityResolver
{
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException
{
// At this point, systemId is always absolutized to the current working directory,
// even though the XML document specified it as relative.
// E.g. "file:///H:/mydoc.dtd" instead of just "mydoc.dtd"
// Why??? How can I prevent this???
SgmlEntity entity = findEntityFromDatabase(systemId);
InputSource is = new InputSource(new ByteArrayInputStream(entity.getContents()));
is.setPublicId(publicId);
is.setSystemId(systemId);
return is;
}
}
I tried both using DOM (DocumentBuilder) and SAX (XMLReader), set the entity resolver to MyEntityResolver (i.e. setEntityResolver(new MyEntityResolver())
), but systemId
in MyEntityResolver#resolveEntity(String publicId, String systemId)
is always being absolutized to the current working directory.
I also tried calling setFeature("http://xml.org/sax/features/resolve-dtd-uris", false);
, but that didn't help anything.
So how can I achieve what I wanted?
Thanks!
Apparently, there is another interface called EntityResolver2 which is the extension of the old EntityResolver. (Talk about confusing names!)
Anyway, I found that EntityResolver2
achieved what I wanted, that is, it does not make any changes to the systemId
, so it will always exactly be what was specified in the XML document.
這篇關(guān)于Java:如何防止 EntityResolver#resolveEntity(String publicId, String systemId) 中的“systemId"被絕對化到當前工作目錄的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!