📄 domparserfortreexml.java
字号:
package cn.dxm.XMLAnaysis.Dom;
import java.io.File;
import java.util.Map;
import java.util.Vector;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
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;
/**
* @author th
*
*/
public class DomParserForTreeXML {
DocumentBuilderFactory dbf;
DocumentBuilder db;
Vector container=new Vector();
private static JTree tree=null;
private static String xmlURL = null;
/*
* 构造函数,为解析器进行初始化
*/
public DomParserForTreeXML() {
super();
try {
dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* 开始解析XML文档,调用getStr方法,遍历所有节点(元素,元素内容,属性)
*/
public void ParserXML() {
Document doc = null;
String filepath = null;
if (xmlURL != null) {
filepath = this.xmlURL;
} else {
DomParserForPathSet dom = new DomParserForPathSet();
Map map = dom.ParserXML("src/ParameterSet.xml");
filepath = (String) map.get("TreeXmlPath");
}
File docfile = new File(filepath);
try {
doc = db.parse(docfile);
Element root = doc.getDocumentElement();
getStr(root);
} catch (Exception f) {
f.printStackTrace();
}
}
private void getStr(Element elem) {
String srcKey=null;
String key = null;
String value = null;
try {
String name = elem.getTagName();
srcKey=key;
key = name;
DefaultMutableTreeNode root=new DefaultMutableTreeNode(name);
NodeList childrenNodes = elem.getChildNodes();
for (int i = 0; i < childrenNodes.getLength(); i++) {
Node temp = childrenNodes.item(i);
if (temp.getNodeType() == Node.ELEMENT_NODE) {
getStr((Element) temp);
System.out.println("----------"+temp.getTextContent());
}
if (temp.getNodeType() == Node.TEXT_NODE) {
String content = temp.getTextContent();
System.out.println("key is.. " + key);
if (!content.trim().equals("")) {
value = content;
System.out.println("value is: " + temp.getNodeValue());
}else{
System.out.println("value is space"+temp.getNodeValue());
}
NamedNodeMap attributes = elem.getAttributes();
int attrsize = attributes.getLength();
if (attrsize > 0) {
for (int j = 0; j < attrsize; j++) {
Attr attrtemp = (Attr) attributes.item(j);
String attrname = attrtemp.getName();
String attrvalue = attrtemp.getValue();
}
}
}
}
} catch (Exception g) {
g.printStackTrace();
}
}
public void walkTree(){}
/**
* @param args
*/
public static void main(String[] args) {
DomParserForTreeXML parser = new DomParserForTreeXML();
parser.ParserXML();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -