具有IBM Websphere依赖性的SAXParser实现

问题描述 投票:1回答:1

我正试图从S.O.的Java专家那里得到一些帮助。关于这个问题。我在很长一段时间的项目中遇到了一个XMLParser的旧实现...在我看来这个实现是不正确的,或者可以改进..我想知道是否有人可以指出要做什么,意见会非常感谢...

这是一个带有pom.xml的maven项目,用于依赖关系btw ...

问题...

enter image description here所以基本上有人在项目中使用SAXParser类直接从IBM内部JRE ...

我如何将这种代码的和平转换为免于WAS(Websphere Aplication Server)的依赖?

    public boolean parse(){
    boolean res = false;
    try {
        SAXParser p = new SAXParser(); // Need to replace this for better aproach
        p.setContentHandler(this); // Need to replace this for better aproach
        InputSource inputSource = new InputSource(new StringReader(source));
        if (inputSource != null){
            p.parse(inputSource); // Need to replace this for better aproach
        }
        res = true;
    } 
    catch (Exception e) {
        System.err.println("public void parse()"+e.getLocalizedMessage());
        res= false;
        e.printStackTrace();
    }
    return res;
}

UPDATE

迁移成功:)

...
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
...
public boolean parse(){
    boolean res = false;
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        javax.xml.parsers.SAXParser saxParser = spf.newSAXParser();

        XMLReader xmlReader = saxParser.getXMLReader();
        xmlReader.setContentHandler(this);

        InputSource inputSource = new InputSource(new StringReader(source));
        if (inputSource != null){
            xmlReader.parse(inputSource);
        }
        res = true;
    } 
    catch (Exception e) {
        System.err.println("public void parse()"+e.getLocalizedMessage());
        res= false;
        e.printStackTrace();
    }
    return res;
}
java xml-parsing saxparser
1个回答
1
投票

您可以从javax.xml.parsers.SAXParserFactory请求javax.xml.parsers.SAXParser,而不是显式构建SAXParser实现:

   SAXParserFactory spf = SAXParserFactory.newInstance();
   spf.setNamespaceAware(true);
   SAXParser saxParser = spf.newSAXParser();

这些代码行创建一个SAXParserFactory实例,由javax.xml.parsers.SAXParserFactory系统属性的设置决定。

这是来自the Java tutorial for Parsing an XML file using SAX

然后你可以从SAXParser获取XMLReader,设置contentHandler,并从InputSource解析xml:

XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(new WhateverYouNameYourContentHandler());
xmlReader.parse(inputSource);
© www.soinside.com 2019 - 2024. All rights reserved.