import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class XmlParser extends DefaultHandler { public void parseXml(String xmlString) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); parser.parse(new InputSource(new StringReader(xmlString)), this); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { } @Override public void endElement(String uri, String localName, String qName) throws SAXException { } @Override public void characters(char[] ch, int start, int length) throws SAXException { } } import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; public class XmlBinder { public String marshalXml(Object object) throws JAXBException { JAXBContext context = JAXBContext.newInstance(object.getClass()); Marshaller marshaller = context.createMarshaller(); StringWriter writer = new StringWriter(); marshaller.marshal(object, writer); return writer.toString(); } public Object unmarshalXml(String xmlString, Class<?> objectType) throws JAXBException { JAXBContext context = JAXBContext.newInstance(objectType); Unmarshaller unmarshaller = context.createUnmarshaller(); StringReader reader = new StringReader(xmlString); return unmarshaller.unmarshal(reader); } } import org.apache.xerces.parsers.DOMParser; import org.w3c.dom.Document; import org.xml.sax.InputSource; public class XmlParser { public Document parseXml(String xmlString) throws Exception { DOMParser parser = new DOMParser(); parser.parse(new InputSource(new StringReader(xmlString))); return parser.getDocument(); } }


上一篇:
下一篇:
切换中文