Advertisement
Fabbian

XML

Jan 14th, 2015
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. package com.dream.data.xml;
  2.  
  3. import java.io.File;
  4. import java.util.LinkedList;
  5.  
  6. import javax.xml.parsers.DocumentBuilderFactory;
  7.  
  8. import org.w3c.dom.Document;
  9. import org.w3c.dom.Node;
  10.  
  11. public abstract class XMLDocument
  12. {
  13. abstract protected void parseDocument(Document doc);
  14.  
  15. public void load(File documentFile) throws Exception
  16. {
  17. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  18. factory.setValidating(false);
  19. factory.setIgnoringComments(true);
  20. parseDocument(factory.newDocumentBuilder().parse(documentFile));
  21. }
  22.  
  23. public static String get(Node n, String item)
  24. {
  25. final Node d = n.getAttributes().getNamedItem(item);
  26. if (d == null)
  27. {
  28. return "";
  29. }
  30. final String val = d.getNodeValue();
  31. if (val == null)
  32. {
  33. return "";
  34. }
  35. return val;
  36. }
  37.  
  38. public static boolean get(Node n, String item, boolean dflt)
  39. {
  40. final Node d = n.getAttributes().getNamedItem(item);
  41. if (d == null)
  42. {
  43. return dflt;
  44. }
  45. final String val = d.getNodeValue();
  46. if (val == null)
  47. {
  48. return dflt;
  49. }
  50. return Boolean.parseBoolean(val);
  51. }
  52.  
  53. public static int get(Node n, String item, int dflt)
  54. {
  55. final Node d = n.getAttributes().getNamedItem(item);
  56. if (d == null)
  57. {
  58. return dflt;
  59. }
  60. final String val = d.getNodeValue();
  61. if (val == null)
  62. {
  63. return dflt;
  64. }
  65. return Integer.parseInt(val);
  66. }
  67.  
  68. public static long get(Node n, String item, long dflt)
  69. {
  70. final Node d = n.getAttributes().getNamedItem(item);
  71. if (d == null)
  72. {
  73. return dflt;
  74. }
  75. final String val = d.getNodeValue();
  76. if (val == null)
  77. {
  78. return dflt;
  79. }
  80. return Long.parseLong(val);
  81. }
  82.  
  83. public static boolean isNodeName(Node node, String name)
  84. {
  85. return (node != null) && node.getNodeName().equals(name);
  86. }
  87.  
  88. public static LinkedList<Node> getNodes(Node node)
  89. {
  90. LinkedList<Node> list = new LinkedList<>();
  91. for (Node n = node.getFirstChild(); n != null; n = n.getNextSibling())
  92. {
  93. list.add(n);
  94. }
  95. return list;
  96. }
  97.  
  98. public static LinkedList<Node> getNodes(Node node, String name)
  99. {
  100. LinkedList<Node> list = new LinkedList<>();
  101. for (Node n = node.getFirstChild(); n != null; n = n.getNextSibling())
  102. {
  103. if (isNodeName(n, name))
  104. {
  105. list.add(n);
  106. }
  107. }
  108. return list;
  109. }
  110. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement