Guest User

Untitled

a guest
Jul 21st, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. public class Class1
  2. {
  3. public Document doc;
  4.  
  5. public void initFileXML()
  6.  
  7. DocumentBuilder docbuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
  8. doc = docbuilder.parse(FILE_NAME);
  9. doc.normalize();
  10.  
  11. }
  12.  
  13.  
  14. public void writeFileXML()
  15. {
  16. Transformer transformer = TransformerFactory.newInstance().newTransformer();
  17. transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes");
  18. DOMSource source = new DOMSource(doc);
  19. FileOutputStream file = new FileOutputStream(FILE_NAME);
  20. StreamResult result = new StreamResult(file);
  21. transformer.transform(source, result);
  22. }
  23.  
  24.  
  25. public void readXML()
  26. {
  27. NodeList nodelist = doc.getElementsByTagName("taskParent");
  28.  
  29. do
  30. {
  31. Node node = nodelist.item(i);
  32. //и выводим в консоль
  33. System.out.println(node.getTextContent());
  34.  
  35. }while(++i < nodelist.getLength());
  36. }
  37.  
  38.  
  39.  
  40. //И еще много разных методов
  41. ...
  42. ...
  43. }
  44.  
  45. <taskParent>
  46. <taskChild1>Текст1</taskChild1>
  47. <taskChild2>Текст2</taskChild2>
  48. <taskChild3>Текст3</taskChild3>
  49. </taskParent>
  50.  
  51. public class Class2
  52. {
  53. public static void main(String[] args)
  54. {
  55. int i = 0;
  56. Class1 xml = new Class1();
  57. xml.initFileXML();//законнектимся к FILE_NAME
  58.  
  59. //Добавим узлы
  60. ...
  61. ТекстA
  62. ...
  63. ТекстB
  64. ...
  65. ТекстD
  66. ...
  67.  
  68. //и сразу же их считываем
  69. xml.readXML();
  70.  
  71. //запишем изменения
  72. xml.writeFileXML();
  73.  
  74. }
  75. }
  76.  
  77. <taskParent>
  78. <taskChild1>Текст1</taskChild1>
  79. <taskChild2>Текст2</taskChild2>
  80. <taskChild3>Текст3</taskChild3>
  81. </taskParent>
  82. <taskParent>
  83. <taskChild1>ТекстA</taskChild1>
  84. <taskChild2>ТекстB</taskChild2>
  85. <taskChild3>ТекстD</taskChild3>
  86. </taskParent>
  87.  
  88. Текст1
  89. Текст2
  90. Текст3
  91.  
  92. ТекстAТекстBТекстD
  93.  
  94. ТекстA
  95. ТекстB
  96. ТекстD , а оно отображает в одну строчку
  97.  
  98. ТекстAТекстBТекстD
  99.  
  100. Текст1
  101. Текст2
  102. Текст3
  103.  
  104. ТекстA
  105. ТекстB
  106. ТекстD , т.е. как и нужно
Add Comment
Please, Sign In to add comment