dom4j基本使用

1.xml文档

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<cons>
    <con number="test">this is a test</con>
</cons>

2.读取xml中的属性值

     SAXReader saxReader = new SAXReader();
        Document document=saxReader.read("D:/123.xml");
        Element rootElement=document.getRootElement();
        List<Element>stEls=rootElement.elements();

        String test="";

        for(Element stEl:stEls){
           String number=stEl.attributeValue("number");
           if(number.equals("test")){
               test=stEl.getText();
           }
        }

3.修改xml中的属性值

      SAXReader saxReader = new SAXReader();
            Document document=saxReader.read("D:/123.xml");
            Element rootElement=document.getRootElement();
            List<Element>stEls=rootElement.elements();


            for(Element stEl:stEls){

                String number=stEl.attributeValue("number");
                if(number.equals("test")){
                    stEl.setText(test);
                }
               
            }

            File f = new File("D:\\123.xml");

            XMLWriter output = new XMLWriter(new FileWriter(f));
            output.write(document);
            output.close();

 

posted @ 2022-09-26 18:16  Xyang  阅读(36)  评论(0编辑  收藏  举报
hi