1、使用JAVA javax.xml.parsers ,org.w3c.dom,org.xml.sax 下的相关类来实现,(DocumentBuilder,DocumentBuilderFactory,Document,Element,Node,NodeList)
XML文件内容如下:
- <struts>
- <package name="dotashop-default" namespace="/" extends="struts-default">
- <action name="index">
- <result>/index.jsp</result>
- <result>/index2.jsp</result>
- <result>/index3.jsp</result>
- <result>/index4.jsp</result>
- <result>/index5.jsp</result>
- <result>/index6.jsp</result>
- <result>/index7.jsp</result>
- <result>/index8.jsp</result>
- </action>
- </package>
- </struts>
要求读出标签<result></result>内的内容?
Java代码实现如下:
- import java.io.File;
- import java.io.IOException;
- import javax.xml.parsers.DocumentBuilder;
- import javax.xml.parsers.DocumentBuilderFactory;
- import javax.xml.parsers.ParserConfigurationException;
- import org.w3c.dom.Document;
- import org.w3c.dom.Element;
- import org.w3c.dom.Node;
- import org.w3c.dom.NodeList;
- import org.xml.sax.SAXException;
- public class S {
- public static void main(String[] args) {
- try {
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder db = factory.newDocumentBuilder();
- Document doc = db.parse(new File("E:/JavaWork/test/src/com/test/struts.xml"));
- Element elmtInfo = doc.getDocumentElement();
- NodeList nodes = elmtInfo.getChildNodes();
- int m = 1;
- for (int i = 0; i < nodes.getLength(); i++) {
- Node result = nodes.item(i);
- if (result.getNodeType() == Node.ELEMENT_NODE && result.getNodeName().equals("package")) {
- NodeList ns = result.getChildNodes();
- for (int j = 0; j < ns.getLength(); j++) {
- Node record = ns.item(j);
- if (record.getNodeType() == Node.ELEMENT_NODE && record.getNodeName().equals("action")) {
- NodeList ks = record.getChildNodes();
- for (int k = 0; k < ks.getLength(); k++) {
- Node re = ks.item(k);
- if (re.getNodeType() == Node.ELEMENT_NOD && re.getNodeName().equals("result")) {
- System.out.println(m + ": "+ re.getTextContent());
- m++;
- }
- }
- }
- }
- }
- }
- } catch (ParserConfigurationException e) {
- e.printStackTrace();
- } catch (SAXException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
运行结果:
1: /index.jsp
2: /index2.jsp
3: /index3.jsp
4: /index4.jsp
5: /index5.jsp
6: /index6.jsp
7: /index7.jsp
8: /index8.jsp
转载于:https://blog.51cto.com/lossie/1075104