Java操作XML之jdom的使用

Java操作XML,推荐使用jdom类库来操作,流程还是一样,下载JAR,然后加载到项目库中,接下来清理项目。

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <stu id="1">
        <name>张无忌1号</name>
        <age>22</age>
    </stu>
    <stu id="2">
        <name>李楚楚1号</name>
        <age>18</age>
    </stu>
</root>

 


import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;

public class JdomStu {

    public static void main(String[] args) throws JDOMException, IOException {
//操作XML字符串
//         String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><stu id=\"1\"><name>张无忌</name><age>22</age></stu><stu id=\"2\"><name>李楚楚</name><age>18</age></stu></root>";
//        StringReader reader = new StringReader(xmlStr);
//        InputSource source = new InputSource(reader);
//        SAXBuilder saxBuilder = new SAXBuilder();
//        Document doc = saxBuilder.build(source);
        /**
         * 操作XML文件
         */
        SAXBuilder saxBuilder = new SAXBuilder();
        Document doc = saxBuilder.build(new File("src/demo.xml"));
        Element rootElement = doc.getRootElement();
        List nodeEles = rootElement.getChildren("stu");
        Element firstEle = (Element) nodeEles.get(0);
        System.out.println("获取第一个stu节点的id属性值:" + firstEle.getAttributeValue("id"));
        System.out.println("节点个数:" + nodeEles.size());
        for (Object nodeEle : nodeEles) {
            Element curEle = (Element) nodeEle;
            System.out.printf("ID:%d,姓名:%s,年龄:%d\n", Integer.parseInt(curEle.getAttributeValue("id")), curEle.getChildText("name"), Integer.parseInt(curEle.getChildText("age")));
        }

    }

}

 

发布者:天南

一个好人

留下评论

电子邮件地址不会被公开。 必填项已用*标注