?? xmlparser.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 + -