package lawyee.bigdata.dac.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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;
//讀取xml模型,生成solr schema.xml文件的field
public class XMLToSchemaField {
public static void main(String[] args) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("C:\\test.xml");
Element element = document.getDocumentElement();
traversNode(element);
// 打印list
for (String s : lstXPath) {
System.out.println(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void traversNode(Element element) {
if (element.getNodeName() == null && element.getNodeName() == "") {
return;
}
getXPath(element);
NodeList lstNode = element.getChildNodes();
int count = lstNode.getLength();
for (int i = 0; i < count; i++) {
Node node = lstNode.item(i);
String nodeName = node.getNodeName();
if (nodeName.equals("#text")) {
continue;
}
Element e = (Element) node;
traversNode(e);
}
}
public static List<String> lstXPath = new ArrayList();
private static void getXPath(Node node) {
String xpath = getNodeXPath(node);
NamedNodeMap atts = node.getAttributes();
for (int i = 0; i < atts.getLength(); i++) {
Node att = atts.item(i);
String attXpath = xpath + "/@" + att.getNodeName();
lstXPath.add(attXpath);
}
}
public static String getNodeXPath(Node node) {
String xpath = "";
XPath = "";
if (node == null) {
return xpath;
}
recurNode(node);
xpath = XPath;
return xpath;
}
private static String XPath = "";
private static void recurNode(Node node) {
String nodeName = node.getNodeName();
XPath = "/" + nodeName + XPath;
Node preNode = node.getParentNode();
if (preNode != null && !preNode.getNodeName().contains("#")) {
recurNode(preNode);
}
}
}
java