1

大家好,这是我在这里的第一个问题,我不是程序员。

我想生成一个站点地图。我正在使用 webcrawler (crawler.dev.java.net) 抓取一个网站。有没有办法对我得到的数据使用 sax 解析器?

我还使用了 jtidy,并将主页 html 数据转换为 xml 文件。

我很困惑有这么多的 sax 解析器,不知道它们之间的区别以及选择哪一个。

我想访问 html 标签的属性,但我不能用 webcrawler 做到这一点,或者我不知道该怎么做

org.xml.sax 和所有其他包有什么区别?

4

1 回答 1

0

Java 提供了一种通过 JAXP 与 SAX 解析器交互的标准方式(参见下面的代码)。要在 SAX 解析器之间切换,通常只需将解析器 jar 添加到类路径中,代码保持不变。

您可以按如下方式进行 sax 解析:

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

public class Demo {

    public static void main(String[] args) throws Exception {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xmlReader = sp.getXMLReader();
        xmlReader.setContentHandler(new MyContentHandler());
        xmlReader.parse(input);

    }

    private static class MyContentHandler implements ContentHandler {

        public void setDocumentLocator(Locator locator) {
        }

        public void startDocument() throws SAXException {
        }

        public void endDocument() throws SAXException {
        }

        public void startPrefixMapping(String prefix, String uri)
                throws SAXException {
        }

        public void endPrefixMapping(String prefix) throws SAXException {
        }

        public void startElement(String uri, String localName, String qName,
                Attributes atts) throws SAXException {
        }

        public void endElement(String uri, String localName, String qName)
                throws SAXException {
        }

        public void characters(char[] ch, int start, int length)
                throws SAXException {
        }

        public void ignorableWhitespace(char[] ch, int start, int length)
                throws SAXException {
        }

        public void processingInstruction(String target, String data)
                throws SAXException {
        }

        public void skippedEntity(String name) throws SAXException {
        }

    }

}
于 2010-09-23T13:59:32.560 回答