Advertisement
teleias

XML [Reading + Simple Visualization]

Sep 2nd, 2015
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.88 KB | None | 0 0
  1. /// Summary:
  2. ///  Use this class to read/visualize XML.
  3. ///  Write your own visualizations by deriving your own Visualization classes.
  4.  
  5. /// Limitations:
  6. ///  Must be XML, any amount of nodes or attributes should work.
  7.  
  8. /// Author:
  9. ///  Austin Takechi
  10.  
  11. /// Date:
  12. ///  9/2/2015
  13.  
  14. /// Licensing:
  15. ///  Do whatever you want with it.
  16.  
  17. import java.io.File;
  18. import java.io.IOException;
  19. import java.util.ArrayList;
  20. import java.util.HashMap;
  21. import java.util.List;
  22. import javax.xml.parsers.DocumentBuilder;
  23. import javax.xml.parsers.DocumentBuilderFactory;
  24. import javax.xml.parsers.ParserConfigurationException;
  25. import org.w3c.dom.Document;
  26. import org.w3c.dom.NamedNodeMap;
  27. import org.w3c.dom.Node;
  28. import org.w3c.dom.NodeList;
  29. import org.xml.sax.SAXException;
  30.  
  31. public class Parser {
  32.    
  33.     public final void Load(String filePath)
  34.     {
  35.         //Here's where you can switch visualizers.
  36.        
  37.         //An example of my default Visualizer:
  38.         Load(filePath, new Visualizer());
  39.        
  40.         //An example of an overriding Visualizer:
  41.         Load(filePath, new EmptyVisualizer());
  42.     }
  43.     public final void Load(String filePath, Visualizer visualizer)
  44.     {
  45.         try {
  46.             //Stuff needed for DOM parsing.
  47.             DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  48.             DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  49.             File file = new File(filePath);
  50.             Document doc = dBuilder.parse(file);
  51.            
  52.             //We will now open and visualize each item in root's childNodes.
  53.             for(int i = 0; i < doc.getChildNodes().getLength(); i++)
  54.             {
  55.                 visualizer.Visualize(
  56.                         Open(doc.getChildNodes().item(i))
  57.                         );
  58.             }
  59.        
  60.         //Below are some try catches. Do with them what you will I suppose.
  61.         } catch (ParserConfigurationException e) {
  62.             // TODO Auto-generated catch block
  63.             e.printStackTrace();
  64.         } catch (SAXException e) {
  65.             // TODO Auto-generated catch block
  66.             e.printStackTrace();
  67.         } catch (IOException e) {
  68.             // TODO Auto-generated catch block
  69.             e.printStackTrace();
  70.         }
  71.        
  72.     }
  73.    
  74.     //XML nodes have information but it's a bit much.
  75.     //To simplify it down, we're going to be using just this class, with only three values.
  76.     //All our information will be put into here, and then visualization will use this class to visualize.
  77.     protected final CustomNode Open(Node node)
  78.     {
  79.         //We need to obtain three things here
  80.         // 1. the name of the node
  81.         //      /name/
  82.         // 2. the attributes in this node
  83.         //      /information/
  84.         // 3. the children of this node
  85.         //      /children/
  86.        
  87.         //Name is the easiest so we'll just get that immediately.
  88.         String name = node.getNodeName();
  89.        
  90.         //The attributes are stored in key:value form,
  91.         // so we'll place them into a more typical structure, the hashMap.
  92.         HashMap<String, String> information = new HashMap<String, String>();
  93.        
  94.         //The children will be found later in this function,
  95.         // so we'll make a list to place them into later.
  96.         List<CustomNode> children = new ArrayList<CustomNode>();
  97.        
  98.         //If this node has attributes, we want to get them.
  99.         // Not every node has attributes though, so we should check first.
  100.         if(node.hasAttributes())
  101.         {
  102.             //Get all the attributes and then foreach through them.
  103.             // Can't actually use the foreach pattern because namedNodeMap isn't iterable.
  104.             // So we just forloop from 0 to length.
  105.             NamedNodeMap attributeList = node.getAttributes();
  106.             for(int i = 0; i < attributeList.getLength(); i++)
  107.             {
  108.                 Node attribute = attributeList.item(i);
  109.                 //Simply add the attribute's name and value into our hashmap.
  110.                 //I don't think xmlNodes have any other information useful to us.
  111.                 information.put(attribute.getNodeName(), attribute.getNodeValue());
  112.             }              
  113.         }
  114.        
  115.         //If this node has children, we want to recurse through them.
  116.         // But just like attributes, not every node has children, so we'll check.
  117.         if(node.hasChildNodes())
  118.         {
  119.             //Get all the childNodes and then foreach through them.
  120.             // Unfortunately can't foreach either..
  121.             // So we just forloop from 0 to length like before.
  122.             NodeList nodeList = node.getChildNodes();
  123.             for(int i = 0; i < nodeList.getLength(); i++)
  124.             {
  125.                 Node child = nodeList.item(i);
  126.                 //Check to see if the node is of type ElementNode
  127.                 // If it isn't, then it's some empty whitespace and we should ignore it.
  128.                 // For whatever reason, XML actually reads whitespace as nodes? I don't get it.
  129.                 // Anyways, just ignore it.
  130.                 if(child.getNodeType() == Node.ELEMENT_NODE)
  131.                 {
  132.                     //We're going to open the child xmlNode recursively.
  133.                     //It returns back a childCustomNode, and since it's one of our CustomNode's
  134.                     // children, we'll add that childCustomNode to our list of children.
  135.                     CustomNode childCustomNode = Open(child);
  136.                     children.add(childCustomNode);
  137.                 }
  138.             }
  139.         }
  140.        
  141.         //We have obtained the
  142.         // /name/
  143.         // /information/
  144.         // /children/
  145.         //so now we will construct a CustomNode around those values and return it.
  146.        
  147.         CustomNode customNode = new CustomNode(
  148.                 name,
  149.                 information,
  150.                 children
  151.                 );
  152.         return customNode;
  153.     }
  154.    
  155.     //CustomNode:
  156.     //CustomNode will have only three simple properties
  157.     // 1. a name to identify it
  158.     // 2. a hashmap of properties
  159.     // 3. a list of children CustomNodes
  160.     protected final class CustomNode
  161.     {
  162.         //Pretty obviously a constructor.
  163.         //Only time values are set are immediately at their inception.
  164.         //Note: I use name_ as the parameter name. That's just a naming convention I use, I don't know what's official.
  165.         // I find it easier than doing
  166.         /*
  167.          * String x;
  168.          * void foo(String x){
  169.          *   this.x = x;
  170.          * }
  171.          */
  172.         protected CustomNode(String name_, HashMap<String, String> information_, List<CustomNode> children_)
  173.         {
  174.             name = name_;
  175.             information = information_;
  176.             children = children_;
  177.         }
  178.        
  179.         //Private fields to disallow outside modification.
  180.         private String name;
  181.         private HashMap<String, String> information;
  182.         private List<CustomNode> children;
  183.        
  184.         //Some getters to retrieve the values.
  185.         //I don't need to explain these.
  186.         public String getName()
  187.         {
  188.             return name;
  189.         }
  190.         public HashMap<String, String> getInformation(){
  191.             return information;
  192.         }
  193.         public List<CustomNode> getChildren(){
  194.             return children;
  195.         }
  196.     }
  197.    
  198.    
  199.     //Visualization:
  200.     //To create your own visualization,
  201.     // Simply derive a child from this class
  202.     // And give it an overriding Visualize() function.
  203.     protected class Visualizer
  204.     {
  205.         //Overload Visualize(..) to take one argument
  206.         public void Visualize(CustomNode customNode)
  207.         {
  208.             Visualize(customNode, 0);
  209.         }
  210.         //Recursively step through each node and child node,
  211.         // printing out the name and information, then
  212.         // repeating for child.
  213.         private void Visualize(CustomNode customNode, int depth)
  214.         {
  215.             //We're going to build a string to output.
  216.             String information = "";
  217.             //Prepend /depth/ number of tabs.
  218.             for(int i = 0; i < depth; i++)
  219.             {
  220.                 information += "\t";
  221.             }
  222.             //Append the name.
  223.             information += customNode.getName()+"> ";
  224.             //Step through the hashmap and add each key/val.
  225.             for(String key : customNode.getInformation().keySet())
  226.             {
  227.                 String val = customNode.getInformation().get(key);
  228.                 information += String.format("(%s: %s) ", key, val);
  229.             }
  230.             System.out.println(information);
  231.             //Recursively descend through all the children and repeat.
  232.             for(CustomNode child : customNode.getChildren())
  233.             {
  234.                 Visualize(child, depth+1);
  235.             }
  236.         }      
  237.     }
  238.    
  239.     //An empty extension of the visualizer as an example.
  240.     protected class EmptyVisualizer extends Visualizer
  241.     {
  242.         @Override
  243.         public void Visualize(CustomNode customNode)
  244.         {
  245.             //You could write your own visualization here if you wanted.
  246.         }
  247.     }
  248.    
  249.    
  250.    
  251.     //Start the code
  252.     public static void main(String[] args)
  253.     {
  254.         //Don't use my static void main, this is just example usage.
  255.         //Assumes a local path, you could define an absolute one if you wanted.
  256.         String filePath = "test.xml";
  257.         new Parser().Load(filePath);
  258.     }
  259.    
  260. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement