添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class XMLParseTest { @Test public void testParse() throws JDOMException, IOException { SAXBuilder sax = new SAXBuilder(); File file = new File("path/to/input.xml"); FileInputStream fis = new FileInputStream(file); Document root = sax.build(fis); Node node = convertToNode(root.getRootElement()); System.out.println(node); String str = convertToXml(node, ""); System.out.println(str); File outfile = new File("path/to/output.xml"); FileOutputStream fos = new FileOutputStream(outfile); fos.write(str.getBytes(StandardCharsets.UTF_8)); private static final String space = " "; private String convertToXml(Node node, String intend) { StringBuilder sb = new StringBuilder(); sb.append(intend).append("<").append(node.getTagName()).append(">"); if (node.getChildren().isEmpty()) { sb.append(node.getContent()); } else { sb.append("\n"); node.getChildren().sort(Comparator.comparing(Node::getTagName)); for (Node child : node.getChildren()) { sb.append(convertToXml(child, intend + space)); sb.append(intend).append("\n"); return sb.toString(); private Node convertToNode(Element root) { Node node = new Node(); List children = root.getChildren(); for (Element child : children) { node.getChildren().add(convertToNode(child)); node.setTagName(root.getName()); node.setContent(root.getTextTrim()); return node; static String xmlStr = ""; class Node { String tagName; String content; List children = new ArrayList<>(); public String getTagName() { return tagName; public void setTagName(String tagName) { this.tagName = tagName; public String getContent() { return content; public void setContent(String content) { this.content = content; public List getChildren() { return children; public void setChildren(List children) { this.children = children; @Override public String toString() { this.getChildren().sort(Comparator.comparing(Node::getTagName)); StringBuilder sb = new StringBuilder(); sb.append("'").append(this.tagName).append("'").append(":").append("{"); for (int i = 0; i < children.size(); i++) { Node child = children.get(i); if(child.getChildren().isEmpty()) { sb.append("'").append(child.getTagName()).append("'").append(":").append("'").append(child.getContent()).append("'"); if (i != children.size() - 1) { sb.append(","); } else { sb.append(child.toString()); sb.append("}"); return sb.toString();