日期:2014-05-18  浏览次数:20694 次

请教java如何操作xml文件
求助

------解决方案--------------------
dom4j
------解决方案--------------------
通过dom或SAX解析
------解决方案--------------------
public class Sax extends DefaultHandler {

/**
* @param args
* @throws SAXException 
* @throws ParserConfigurationException 
* @throws IOException 
*/
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {

SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setValidating(false);
spf.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
spf.setFeature("http://xml.org/sax/features/namespaces", true);
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();

xr.setContentHandler(new Sax());
xr.setErrorHandler(new Sax());

InputSource is = new InputSource("c:\\sax.xml");
xr.parse(is);
}


public void startDocument() throws SAXException {

System.out.println("start to read xml");
}


public void endDocument() throws SAXException {

System.out.println("end of reading xml");
}


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

// System.out.println("uri----" + uri);
// System.out.println("localName----" + localName);
// System.out.println("qName----" + qName);
// Method[] methods = attributes.getClass().getMethods();
// for (int i = 0; i < methods.length; i++) {
// Method method = methods[i];
// String name = method.getName();
// if (name.startsWith("get")) {
// Class[] param = method.getParameterTypes();
// if (param.length == 1 && param[0].isPrimitive()) {
// try {
// for (int j = 0; j < attributes.getLength(); j++) {
// String info = name
// + "----"
// + method.invoke(attributes,
// new Object[] { new Integer(j) });
// System.out.println(info);
// }
// } catch (IllegalArgumentException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// }
// }
// System.out.println("----&quo