我想使用“ SAXParser”将任何XML文件解析为“ XMLNode”类的对象列表

XMLNode类

public class XMLNode {

    private String nodeName;
    private String nodeValue;
    private List<XMLNodeAttribute> attributes;
    private boolean isParentNode;
    private List<XMLNode> childNodes;

    //.... getters and setters ....
}


XMLNodeAttribute类

public class XMLNodeAttribute {

    private String name;
    private String value;

    //.... getters and setters ....

}


请帮助我编写解析器类,该类可以将输入作为XML文件并输出List。

先感谢您。

我能够写一些代码。

public class XmlProcesser extends DefaultHandler {

    XMLResponse xmlResponse = null;
    List<XMLNode> resplist  = new ArrayList();
    List<XMLNode> temp  = new ArrayList();
    boolean endtag = false;

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {

         String elementName = localName;
            if ("".equals(elementName)) {
                elementName = qName;
            }
        System.out.println(" Start Ele - " + elementName  );

        //Each attribute

        if (elementName!=null) {
            if (attributes!=null) {
                    for (int pos=0; pos<attributes.getLength(); pos++) {
                        String name = attributes.getLocalName(pos)==null || attributes.getLocalName(pos).trim().length()==0 ? attributes.getQName(pos) : attributes.getLocalName(pos);
                        String value= attributes.getValue(pos);
                        System.out.println(" name - " + name  + "   value - "  + value  );
                    }
                }
        }

    }

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

        String s = new String(ch, start, length);
        System.out.println(" value - " + s   );

        endtag = false;
    }

    @Override
    public void endElement(String uri, String localName,
            String qName) throws SAXException {
        endtag = true;

        String elementName = localName;
            if ("".equals(elementName)) {
                elementName = qName;
            }
        System.out.println(" End Ele - " + elementName  );

    }
}

最佳答案

您可以使用JAXB的UnmarshallerHandler来实现此用例:

    JAXBContext jc = JAXBContext.newInstance(XmlNode.clas);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    UnmarshallerHandler handler = unmarshaller.getUnmarshallerHandler();

    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    XMLReader xr = sp.getXMLReader();
    xr.setContentHandler(handler);
    xr.parse(xml);
    XmlNode xmlNode = (XmlNode) handler.getResult();


完整的例子


http://blog.bdoughan.com/2011/05/jaxb-and-dtd.html

10-06 06:25