Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// Summary:
- /// Use this class to read/visualize XML.
- /// Write your own visualizations by deriving your own Visualization classes.
- /// Limitations:
- /// Must be XML, any amount of nodes or attributes should work.
- /// Author:
- /// Austin Takechi
- /// Date:
- /// 9/2/2015
- /// Licensing:
- /// Do whatever you want with it.
- import java.io.File;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import javax.xml.parsers.DocumentBuilder;
- import javax.xml.parsers.DocumentBuilderFactory;
- import javax.xml.parsers.ParserConfigurationException;
- import org.w3c.dom.Document;
- import org.w3c.dom.NamedNodeMap;
- import org.w3c.dom.Node;
- import org.w3c.dom.NodeList;
- import org.xml.sax.SAXException;
- public class Parser {
- public final void Load(String filePath)
- {
- //Here's where you can switch visualizers.
- //An example of my default Visualizer:
- Load(filePath, new Visualizer());
- //An example of an overriding Visualizer:
- Load(filePath, new EmptyVisualizer());
- }
- public final void Load(String filePath, Visualizer visualizer)
- {
- try {
- //Stuff needed for DOM parsing.
- DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
- File file = new File(filePath);
- Document doc = dBuilder.parse(file);
- //We will now open and visualize each item in root's childNodes.
- for(int i = 0; i < doc.getChildNodes().getLength(); i++)
- {
- visualizer.Visualize(
- Open(doc.getChildNodes().item(i))
- );
- }
- //Below are some try catches. Do with them what you will I suppose.
- } catch (ParserConfigurationException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (SAXException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- //XML nodes have information but it's a bit much.
- //To simplify it down, we're going to be using just this class, with only three values.
- //All our information will be put into here, and then visualization will use this class to visualize.
- protected final CustomNode Open(Node node)
- {
- //We need to obtain three things here
- // 1. the name of the node
- // /name/
- // 2. the attributes in this node
- // /information/
- // 3. the children of this node
- // /children/
- //Name is the easiest so we'll just get that immediately.
- String name = node.getNodeName();
- //The attributes are stored in key:value form,
- // so we'll place them into a more typical structure, the hashMap.
- HashMap<String, String> information = new HashMap<String, String>();
- //The children will be found later in this function,
- // so we'll make a list to place them into later.
- List<CustomNode> children = new ArrayList<CustomNode>();
- //If this node has attributes, we want to get them.
- // Not every node has attributes though, so we should check first.
- if(node.hasAttributes())
- {
- //Get all the attributes and then foreach through them.
- // Can't actually use the foreach pattern because namedNodeMap isn't iterable.
- // So we just forloop from 0 to length.
- NamedNodeMap attributeList = node.getAttributes();
- for(int i = 0; i < attributeList.getLength(); i++)
- {
- Node attribute = attributeList.item(i);
- //Simply add the attribute's name and value into our hashmap.
- //I don't think xmlNodes have any other information useful to us.
- information.put(attribute.getNodeName(), attribute.getNodeValue());
- }
- }
- //If this node has children, we want to recurse through them.
- // But just like attributes, not every node has children, so we'll check.
- if(node.hasChildNodes())
- {
- //Get all the childNodes and then foreach through them.
- // Unfortunately can't foreach either..
- // So we just forloop from 0 to length like before.
- NodeList nodeList = node.getChildNodes();
- for(int i = 0; i < nodeList.getLength(); i++)
- {
- Node child = nodeList.item(i);
- //Check to see if the node is of type ElementNode
- // If it isn't, then it's some empty whitespace and we should ignore it.
- // For whatever reason, XML actually reads whitespace as nodes? I don't get it.
- // Anyways, just ignore it.
- if(child.getNodeType() == Node.ELEMENT_NODE)
- {
- //We're going to open the child xmlNode recursively.
- //It returns back a childCustomNode, and since it's one of our CustomNode's
- // children, we'll add that childCustomNode to our list of children.
- CustomNode childCustomNode = Open(child);
- children.add(childCustomNode);
- }
- }
- }
- //We have obtained the
- // /name/
- // /information/
- // /children/
- //so now we will construct a CustomNode around those values and return it.
- CustomNode customNode = new CustomNode(
- name,
- information,
- children
- );
- return customNode;
- }
- //CustomNode:
- //CustomNode will have only three simple properties
- // 1. a name to identify it
- // 2. a hashmap of properties
- // 3. a list of children CustomNodes
- protected final class CustomNode
- {
- //Pretty obviously a constructor.
- //Only time values are set are immediately at their inception.
- //Note: I use name_ as the parameter name. That's just a naming convention I use, I don't know what's official.
- // I find it easier than doing
- /*
- * String x;
- * void foo(String x){
- * this.x = x;
- * }
- */
- protected CustomNode(String name_, HashMap<String, String> information_, List<CustomNode> children_)
- {
- name = name_;
- information = information_;
- children = children_;
- }
- //Private fields to disallow outside modification.
- private String name;
- private HashMap<String, String> information;
- private List<CustomNode> children;
- //Some getters to retrieve the values.
- //I don't need to explain these.
- public String getName()
- {
- return name;
- }
- public HashMap<String, String> getInformation(){
- return information;
- }
- public List<CustomNode> getChildren(){
- return children;
- }
- }
- //Visualization:
- //To create your own visualization,
- // Simply derive a child from this class
- // And give it an overriding Visualize() function.
- protected class Visualizer
- {
- //Overload Visualize(..) to take one argument
- public void Visualize(CustomNode customNode)
- {
- Visualize(customNode, 0);
- }
- //Recursively step through each node and child node,
- // printing out the name and information, then
- // repeating for child.
- private void Visualize(CustomNode customNode, int depth)
- {
- //We're going to build a string to output.
- String information = "";
- //Prepend /depth/ number of tabs.
- for(int i = 0; i < depth; i++)
- {
- information += "\t";
- }
- //Append the name.
- information += customNode.getName()+"> ";
- //Step through the hashmap and add each key/val.
- for(String key : customNode.getInformation().keySet())
- {
- String val = customNode.getInformation().get(key);
- information += String.format("(%s: %s) ", key, val);
- }
- System.out.println(information);
- //Recursively descend through all the children and repeat.
- for(CustomNode child : customNode.getChildren())
- {
- Visualize(child, depth+1);
- }
- }
- }
- //An empty extension of the visualizer as an example.
- protected class EmptyVisualizer extends Visualizer
- {
- @Override
- public void Visualize(CustomNode customNode)
- {
- //You could write your own visualization here if you wanted.
- }
- }
- //Start the code
- public static void main(String[] args)
- {
- //Don't use my static void main, this is just example usage.
- //Assumes a local path, you could define an absolute one if you wanted.
- String filePath = "test.xml";
- new Parser().Load(filePath);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement