27 ก.ย. 2554

ReadXml

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
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.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XMLReader {
private String out = "";
private HashMap<Node, String> checkEle;
private HashMap<String, Node> mapRoot;
public static void main(String argv[]) throws ParserConfigurationException,
SAXException, IOException {
new XMLReader();
}

public XMLReader() throws ParserConfigurationException, SAXException,
IOException {
DocumentBuilderFactory docBuild = DocumentBuilderFactory.newInstance();
docBuild.setNamespaceAware(false);
docBuild.setIgnoringComments(true);
docBuild.setIgnoringElementContentWhitespace(true);
DocumentBuilder build = docBuild.newDocumentBuilder();
Document doc = build.parse(new File("input.xml"));
Element root = doc.getDocumentElement();
parser(root);
}

public void parser(Element element) {
System.out.println(element.getNodeName());
NodeList list1 = element.getChildNodes();
checkEle = new HashMap<Node, String>();
mapRoot = new HashMap<String, Node>();
parserChildNode(list1,0);
System.out.println(out);
}
public void parserChildNode(NodeList list,int indexChild) {
String tab = "|  |";
for (int i = 0; i < indexChild; i++) {
tab+="|  |";
}
if (list != null) {
for (int i = 0; i < list.getLength(); i++) {
if (!list.item(i).getNodeName().equals("#text")) {
if(mapRoot.get(list.item(i))!=null){
tab = checkEle.get(mapRoot.get(list.item(i).getNodeName()));
}
NamedNodeMap attribute = list.item(i).getAttributes();
if(attribute!=null && attribute.getLength()>0){
String text = "";
if(list.item(i).hasChildNodes())
text = list.item(i).getFirstChild().getTextContent();
if(checkEle.get(list.item(i)) != null)
out += checkEle.get(list.item(i))+"<"+list.item(i).getNodeName()+"> "+text;
else{
out += tab+"<"+list.item(i).getNodeName()+">";
checkEle.put(list.item(i), tab);
}
}
else{
String text = "";
if(list.item(i).hasChildNodes())
text = list.item(i).getFirstChild().getTextContent();
out += tab+"<"+list.item(i).getNodeName()+"> "+text+"\n";
}
if(attribute!=null && attribute.getLength()>0){
for (int j = 0; j < attribute.getLength(); j++) {
out +=attribute.item(j).getNodeName()+"="+attribute.item(j).getNodeValue();
}
out+="\n";
}
if(list.item(i).getChildNodes()!=null){
if(mapRoot.get(list.item(i).getParentNode())== null){
mapRoot.put(list.item(i).getParentNode().getNodeName(),list.item(1));
parserChildNode(list.item(i).getChildNodes(),indexChild++);
}
}
}

}
}
}
}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น