首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Java Web开发 >

请问java怎么操作xml文件

2012-01-24 
请教java如何操作xml文件求助[解决办法]dom4j[解决办法]通过dom或SAX解析[解决办法]public class Sax exte

请教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("----");
}


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

System.out.println("target----" + target);
System.out.println("data----" + data);
}

}

[解决办法]
BufferReader in=new BufferReader(new FileReader(xml文件路径));
DOMParser parser=new DOMParser();
parser.parse(new InputSource(in));


Document doc=parser.getDocument();
然后使用doc.getElementsByTagName("*")获得所有xml中的元素;

[解决办法]
把dom4j放到环境变量下就可以了
[解决办法]
用JDOM

热点排行