jdom当然要引入jdom的jar包了。
没有多余的废话,直接看解析代码:
import java.io.File; import java.io.FileOutputStream; import java.util.List; import org.jdom.Attribute; import org.jdom.Document; import org.jdom.Element; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; public class JDomTest2 { public static void main(String[] args) throws Exception { //JDOM从XML中解析 SAXBuilder builder = new SAXBuilder(); //获得XML文档对象 Document doc = builder.build(new File("jdom.xml")); //得到文档根元素 Element element = doc.getRootElement(); System.out.println(element.getName()); //得到根元素下的hello元素 Element hello = element.getChild("hello"); System.out.println(hello.getText()); //得到hello子元素下的属性 List list = hello.getAttributes(); //得到hello元素下属性的名字和值 for(int i = 0 ;i < list.size(); i++) { Attribute attr = (Attribute)list.get(i); String attrName = attr.getName(); String attrValue = attr.getValue(); System.out.println(attrName + "=" + attrValue); } //删除hello下的world子元素 hello.removeChild("world"); //将文档保存到另一个文件 XMLOutputter out = new XMLOutputter(Format.getPrettyFormat().setIndent(" ")); out.output(doc, new FileOutputStream("jdom2.xml")); } }
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/11723.html