得到XML文档
public static Element getRoot(Path path) throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(path.toFile());
Element root = document.getDocumentElement();
return root;
}
public static Element getRootIgnoring(Path path) throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// 验证xml
factory.setValidating(true);
// 忽略xml中的空白
factory.setIgnoringElementContentWhitespace(true);
// 忽略注释
factory.setIgnoringComments(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(path.toFile());
Element root = document.getDocumentElement();
return root;
}
public static void xmlNodeToString(Element node) {
System.out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
printXml(node);
}
public static void printXml(Element node) {
System.out.print(String.format("%s%s%s%s%s", tier(countParent(node)),
"<", node.getTagName(), getAttrsStr(node), ">"));
boolean leaf = isLeaf(node);
if (leaf) {
System.out.print(node.getTextContent());
} else {
System.out.println();
for (Node n = node.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n instanceof Element) {
printXml((Element) n);
}
}
}
if (leaf) {
System.out.println(String.format("%s%s%s", "</", node.getTagName(), ">"));
} else {
System.out.println(String.format("%s%s%s%s", tier(countParent(node)), "</", node.getTagName(), ">"));
}
}
/**
* 拼接层级
*/
public static String tier(int count) {
if (count == 0) {
return "";
}
StringBuilder sbr = new StringBuilder();
for (int i = 1; i < count; i++) {
sbr.append(" ");
}
return sbr.toString();
}
/**
* 拼接属性
*/
public static String getAttrsStr(Node node) {
NamedNodeMap attrs = node.getAttributes();
if (attrs.getLength() == 0) {
return "";
}
StringBuilder sbr = new StringBuilder();
for (int i = 0; i < attrs.getLength(); i++) {
Node attr = attrs.item(i);
if (i == 0 || i < attrs.getLength()) {
sbr.append(" ");
}
sbr.append(attr.getNodeName()).append("=").append("\"").append(attr.getNodeValue()).append("\"");
}
return sbr.toString();
}
/**
* 子节点数量
*
* @param node
* @return
*/
public static int countChild(Node node) {
int count = 0;
NodeList nodeList = node.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
if (nodeList.item(i) instanceof Element) {
count++;
}
}
return count;
}
/**
* 获取父级数量
*/
public static int countParent(Node node) {
int count = 0;
if (node.getParentNode() != null) {
count++;
count += countParent(node.getParentNode());
}
return count;
}
/**
* 是否子节点
*
* @param node
* @return
*/
public static boolean isLeaf(Node node) {
return countChild(node) == 0;
}
网友评论