⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 xmlparser.java

📁 简单的java http 服务器和客户端源代码
💻 JAVA
字号:
package testHttp.parser;

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 * 
 * <p>
 * Title: XMLParser.java
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright:OnewaveInc Copyright (c) 2007
 * </p>
 * <p>
 * Company: OnewaveInc
 * </p>
 * 
 * @author Zhengrw
 * @version 3.0
 */
public class XMLParser {

	private static final String HEADER = "HEADER";

	private static final String BODY = "BODY";

	public static void parse(String xmlString) throws Exception {

		DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
		DocumentBuilder dombuilder = domfac.newDocumentBuilder();
		Document doc = dombuilder.parse(new InputSource(new StringReader(
				xmlString)));
		Element root = doc.getDocumentElement();
		NodeList messages = root.getChildNodes();
		if (messages != null) {
			for (int i = 0; i < messages.getLength(); i++) {
				Node message = messages.item(i);
				if (message.getNodeType() == Node.ELEMENT_NODE) {
					String messageName = message.getNodeName();
					if (messageName.equalsIgnoreCase(HEADER)) {
						String command = message.getAttributes().getNamedItem(
								"command").getNodeValue();
						System.out.println(command);
					} else if (messageName.equalsIgnoreCase(BODY)) {
						for (Node node = message.getFirstChild(); node != null; node = node
								.getNextSibling()) {
							parseNode(node);
						}
					}
				}
			}
		}
	}

	private static void parseNode(Node node) throws Exception {
		if (node.getNodeType() == Node.ELEMENT_NODE) {
			System.out.println();
			System.out.print(node.getNodeName()+"->");
			int length = node.getAttributes().getLength();
			for (int index = 0; index < length; index++) {
				String title = node.getAttributes().item(index).getNodeName();
				String value = node.getAttributes().item(index).getNodeValue();
				System.out.print(title + ":" + value);
			}
			if (node.hasChildNodes()) {
				for (Node childNode = node.getFirstChild(); childNode != null; childNode = childNode
						.getNextSibling()) {
					parseNode(childNode);
				}
			}
			return;
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -