📄 domparserforpathset.java
字号:
package cn.dxm.XMLAnaysis.Dom;
import java.io.File;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
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 DomParserForPathSet {
DocumentBuilderFactory dbf;
DocumentBuilder db;
private Map elemenetContainer=null;
private static Map map=new HashMap();
/*
* 构造函数,为解析器进行初始化
*/
public DomParserForPathSet() {
super();
try {
dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* 开始解析XML文档,调用getStr方法,遍历所有节点(元素,元素内容,属性)
*/
public Map ParserXML(String filepath) {
Document doc = null;
File docfile = new File(filepath);
String str = "";
try {
doc = db.parse(docfile);
Element root = doc.getDocumentElement();
getStr(root);
} catch (Exception f) {
f.printStackTrace();
}
return map;
}
private void getStr(Element elem) {
String key=null;
String value=null;
try {
String name = elem.getTagName();
key=name;
//System.out.println("name is:"+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);
}
if (temp.getNodeType() == Node.TEXT_NODE) {
String content = temp.getTextContent();
if (!content.trim().equals("")) {
value=content;
//System.out.println("key:"+key);
//System.out.println("value:"+value);
map.put(key, value);
//System.out.println("content is:"+content);
}
}
}
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();
// System.out.println("the attrname is:"+attrname);
// System.out.println("the attrvalue is:"+attrvalue);
}
}
} catch (Exception g) {
g.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String args[]){
DomParserForPathSet d=new DomParserForPathSet();
d.ParserXML("src/ParameterSet.xml");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -