使用JDOM读xml
写一段代码读前面(1)的xml文件,代码如下
SAXBuilder builder = new SAXBuilder(false);
Document doc = builder.build("d:/a.xml");
//获取处理指令并输出
ProcessingInstruction ins = (ProcessingInstruction) doc.getContent(0);
System.out.print("<?" + ins.getTarget() + " ");
List<String> insList = ins.getPseudoAttributeNames();
for(int index = 0; index < insList.size(); index++){
String value = insList.get(index);
System.out.print(value + "=\"" + ins.getPseudoAttributeValue(value) + "\"");
if(index < insList.size() - 1){
System.out.print(" ");
}
}
System.out.println("?>");
//获取DocType并输出
DocType docType = doc.getDocType();
System.out.print("<!DOCTYPE " + docType.getElementName());
System.out.print(" PUBLIC \"" +docType.getPublicID() + "\"");
System.out.println(" \"" + docType.getSystemID() + "\"");
//获取root
Element root = doc.getRootElement();
//输出root的头部
System.out.print("<" +root.getName() + " ");
List<Attribute> rootAttrList = root.getAttributes();
for(int index = 0; index < rootAttrList.size(); index++){
Attribute attr = rootAttrList.get(index);
System.out.print(attr.getName() + "=\"" + attr.getValue() + "\"");
if(index < rootAttrList.size() - 1){
System.out.print(" ");
}
}
System.out.println(">");
//获取子元素
List<Element> childList = root.getChildren();
for(int eleIndex = 0; eleIndex < childList.size(); eleIndex++){
Element element = childList.get(eleIndex);
String elementName = element.getName();
String elementValue = element.getText();
List<Element> innerList = element.getChildren();
if(innerList == null || innerList.size() == 0){
System.out.println("<" + elementName + ">" + elementValue + "</" + elementName + ">");
}else{
System.out.println("<" + elementName + ">");
for(int innerIndex = 0; innerIndex < innerList.size(); innerIndex++){
Element innerElement = innerList.get(innerIndex);
String innerElementName = innerElement.getName();
String innerElementValue = innerElement.getText();
System.out.println("<" + innerElementName + ">" + innerElementValue + "</" + innerElementName + ">");
}
System.out.println("</" + elementName + ">");
}
}
//输出root的结尾
System.out.println("</root>");
最后输出结果如下:
<?xml-stylesheet type="text/xsl" href="products.xsl"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd" <root root="this is root"> <file>c:/a.txt</file> <test> <testInner>test</testInner> </test> </root>