处理Sax Parser中的外部实体和样式表(XML)

时间:2014-06-17 15:42:35

标签: java xml security saxparser

我想忽略外部实体和外部样式表(例如<?xml-stylesheet type="text/xsl" href="......."?>)。

我知道我必须将XMLReader属性设置为忽略外部实体,但我不知道如何忽略样式表...

import org.apache.xerces.parsers.SAXParser;
import org.xml.sax.XMLReader;
//...
final XMLReader parser = new SAXParser();

// Ignore entities
parser.setProperty("http://xml.org/sax/features/external-general-entities", false);

//  IS CORRECT???
parser.setProperty("http://xml.org/sax/features/external-general-entities", false);

还有更多属性可以设置以避免外部实体和样式表吗? 我怎样才能理解样式表中是否有外部实体?

2 个答案:

答案 0 :(得分:1)

external stylesheet declaration是标准processing instruction

您可以通过而不是实现处理程序方法来忽略处理指令:

void processingInstruction(java.lang.String target, java.lang.String data) {}
在您的SAX处理程序中

答案 1 :(得分:1)

为我工作:

public class SaxParser extends DefaultHandler
    implements ContentHandler, DTDHandler, EntityResolver{

public transient static final String STYLE_SHEET_TAG = "xml-stylesheet";
public transient static final String EXTERNAL_ENTITY = "ExternalEntity";

public static void main(String[] args) {
    new SaxParser().execute();
}

public void execute() {
    String pathFileXml = "test/XML.xml";

    final XMLReader parser = new SAXParser();
    parser.setContentHandler(this);
    parser.setDTDHandler(this);
    parser.setEntityResolver(this);

    try {
        parser.parse(pathFileXml);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (SAXException e) {

        if (SaxParser.STYLE_SHEET_TAG.equals(e.getMessage())
                || SaxParser.EXTERNAL_ENTITY.equals(e.getMessage())) {

            System.out.println("CATCH ERRORE");
        }
        e.printStackTrace();
    }
    System.out.println("OK");
}

@Override
public void processingInstruction(String target, String data)
        throws SAXException {
    System.out.println("Processing Instruction");
    System.out.println("PI=> target: " + target + ", data: " + data);

    if (STYLE_SHEET_TAG.equalsIgnoreCase(target.trim())) {
        throw new SAXException(STYLE_SHEET_TAG);
    }
    return;
}
    @Override
    public InputSource resolveEntity(String publicId, String systemId)
        throws IOException, SAXException {

    System.out.println("publicId: " + publicId + ", systemId: " + systemId);
    throw new SAXException(SaxParser.EXTERNAL_ENTITY);


}
}