好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java对XML文件增删改查操作示例

本文实例讲述了java对xml文件增删改查操作。分享给大家供大家参考,具体如下:

xml文件:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<?xml version= "1.0" encoding= "utf-8" ?>

<books>

   <book>

     <name>哈里波特</name>

     <price> 10 </price>

     <memo>这是一本很好看的书。</memo>

   </book>

   <book id= "b02" >

     <name>三国演义</name>

     <price> 10 </price>

     <memo>四大名著之一。</memo>

   </book>

   <book id= "b03" >

     <name>水浒</name>

     <price> 6 </price>

     <memo>四大名著之一。</memo>

   </book>

   <book id= "b04" >

     <name>红楼</name>

     <price> 5 </price>

     <memo>四大名著之一。</memo>

   </book>

</books>

增删改查 test.java

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

import java.io.file;

import java.io.fileoutputstream;

import org.w3c.dom.*;

import javax.xml.parsers.*;

import javax.xml.transform.*;

import javax.xml.transform.dom.domsource;

import javax.xml.transform.stream.*;

import javax.xml.xpath.*;

public class test {

   public static void main(string[] args) {

     documentbuilderfactory factory = documentbuilderfactory.newinstance();

     element thebook = null , theelem = null , root = null ;

     try {

       factory.setignoringelementcontentwhitespace( true );

       documentbuilder db = factory.newdocumentbuilder();

       document xmldoc = (document) db.parse( new file( "test.xml" ));

       root = xmldoc.getdocumentelement();

       // --- 新建一本书开始 ----

       thebook = xmldoc.createelement( "book" );

       theelem = xmldoc.createelement( "name" );

       theelem.settextcontent( "新书" );

       thebook.appendchild(theelem);

       theelem = xmldoc.createelement( "price" );

       theelem.settextcontent( "20" );

       thebook.appendchild(theelem);

       theelem = xmldoc.createelement( "memo" );

       theelem.settextcontent( "新书的更好看。" );

       thebook.appendchild(theelem);

       root.appendchild(thebook);

       system.out.println( "--- 新建一本书开始 ----" );

       output(xmldoc);

       // --- 新建一本书完成 ----

       // --- 下面对《哈里波特》做一些修改。 ----

       // --- 查询找《哈里波特》----

       thebook = (element) selectsinglenode( "/books/book[name='哈里波特']" ,

           root);

       system.out.println( "--- 查询找《哈里波特》 ----" );

       output(thebook);

       // --- 此时修改这本书的价格 -----

       thebook.getelementsbytagname( "price" ).item( 0 ).settextcontent( "15" ); // getelementsbytagname返回的是nodelist,所以要跟上item(0)。另外,getelementsbytagname("price")相当于xpath的".//price"。

       system.out.println( "--- 此时修改这本书的价格 ----" );

       output(thebook);

       // --- 另外还想加一个属性id,值为b01 ----

       thebook.setattribute( "id" , "b01" );

       system.out.println( "--- 另外还想加一个属性id,值为b01 ----" );

       output(thebook);

       // --- 对《哈里波特》修改完成。 ----

       // --- 要用id属性删除《三国演义》这本书 ----

       thebook = (element) selectsinglenode( "/books/book[@id='b02']" , root);

       system.out.println( "--- 要用id属性删除《三国演义》这本书 ----" );

       output(thebook);

       thebook.getparentnode().removechild(thebook);

       system.out.println( "--- 删除后的xml ----" );

       output(xmldoc);

       // --- 再将所有价格低于10的书删除 ----

       nodelist somebooks = selectnodes( "/books/book[price<10]" , root);

       system.out.println( "--- 再将所有价格低于10的书删除 ---" );

       system.out.println( "--- 符合条件的书有 " + somebooks.getlength()

           + "本。 ---" );

       for ( int i = 0 ; i < somebooks.getlength(); i++) {

         somebooks.item(i).getparentnode().removechild(somebooks.item(i));

       }

       output(xmldoc);

       savexml( "test1_edited.xml" , xmldoc);

     } catch (exception e) {

       e.printstacktrace();

     }

   }

   /**

    * 将node的xml字符串输出到控制台

    *

    * @param node

    */

   public static void output(node node) {

     transformerfactory transfactory = transformerfactory.newinstance();

     try {

       transformer transformer = transfactory.newtransformer();

       transformer.setoutputproperty( "encoding" , "gb2312" );

       transformer.setoutputproperty( "indent" , "yes" );

       domsource source = new domsource();

       source.setnode(node);

       streamresult result = new streamresult();

       result.setoutputstream(system.out);

       transformer.transform(source, result);

     } catch (exception e) {

       e.printstacktrace();

     }

   }

   /**

    * 查找节点,并返回第一个符合条件节点

    *

    * @param express

    * @param source

    * @return

    */

   public static node selectsinglenode(string express, object source) {

     node result = null ;

     xpathfactory xpathfactory = xpathfactory.newinstance();

     xpath xpath = xpathfactory.newxpath();

     try {

       result = (node) xpath.evaluate(express, source, xpathconstants.node);

     } catch (xpathexpressionexception e) {

       e.printstacktrace();

     }

     return result;

   }

   /**

    * 查找节点,返回符合条件的节点集。

    * @param express

    * @param source

    * @return

    */

   public static nodelist selectnodes(string express, object source) {

     nodelist result = null ;

     xpathfactory xpathfactory = xpathfactory.newinstance();

     xpath xpath = xpathfactory.newxpath();

     try {

       result = (nodelist) xpath.evaluate(express, source,

           xpathconstants.nodeset);

     } catch (xpathexpressionexception e) {

       e.printstacktrace();

     }

     return result;

   }

   /**

    * 将document输出到文件

    * @param filename

    * @param doc

    */

   public static void savexml(string filename, document doc) {

     transformerfactory transfactory = transformerfactory.newinstance();

     try {

       transformer transformer = transfactory.newtransformer();

       transformer.setoutputproperty( "indent" , "yes" );

       domsource source = new domsource();

       source.setnode(doc);

       streamresult result = new streamresult();

       result.setoutputstream( new fileoutputstream(filename));

       transformer.transform(source, result);

     } catch (exception e) {

       e.printstacktrace();

     }

   }

}

ps:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:

xml 在线压缩/格式化工具: https://tool.tuohang.net/t/xml/

希望本文所述对大家java程序设计有所帮助。

原文链接:https://blog.csdn.net/u013183865/article/details/32165289

查看更多关于Java对XML文件增删改查操作示例的详细内容...

  阅读:13次