0

Does anyone know how to parse this document to get java object in an arrayList of type Node with attributes: node_id relatedroutes description title on_finish_routeid on_starting_routeid level_id waypoint_type name lon lat

for info it is a graphml xml doc. eg.

<node id="L08-022">
      <data key="lat">40.69330963</data>
      <data key="lon">-73.98752537</data>
      <data key="name" />
      <data key="waypoint_type">escalator</data>
      <data key="level_id">1080000</data>
      <data key="on_starting_route" />
      <data key="on_finish_route" />
    </node>
    <node id="L08-023">
      <data key="lat">40.69318355</data>
      <data key="lon">-73.98755793</data>
      <data key="name" />
      <data key="waypoint_type">stairs</data>
      <data key="level_id">1080000</data>
      <data key="on_starting_route" />
      <data key="on_finish_route" />
    </node>
    <node id="L08-024">
      <data key="lat">40.69316844</data>
      <data key="lon">-73.98755873</data>
      <data key="name" />
      <data key="waypoint_type">stairs</data>
      <data key="level_id">1080000</data>
      <data key="on_starting_route" />
      <data key="on_finish_route" />
    </node>

I have tried many ways, really need help, I cannot get the information out i need.

docker dev
  • 91
  • 3
  • 10
  • What ways have you tried? Can you share the code from any of your attempts? Can you describe any specific problems you encountered? That should help to get you some answers. – andrewJames Mar 29 '20 at 20:23
  • @andrewjames I am used to using XMLPullParser where the tags are different in the xml instead of the Data Key pairs and the id in the Node tag itself , i just don't know how to parse this i have had a look at Blueprints and tinkerpop for graphml but really cannot get my head around that and the documentation out there is not helping. Appreciate you having a look for me – docker dev Mar 29 '20 at 20:35
  • Take a look at [JAXB](https://docs.oracle.com/javase/tutorial/jaxb/intro/index.html) and [SAX](https://docs.oracle.com/javase/tutorial/jaxp/sax/parsing.html) as two common ways to parse XML using Java. Write some code, try some different approaches. If you get stuck, you can show your code and ask a specific question (but chances are high that it has already been asked and answered on this site - so check first). Hope that helps! – andrewJames Mar 29 '20 at 20:40
  • @andrewjames All the parsers i have looked at rely upon StartTag End TAG etc.. However these tags in the graphml are either the same, as in or as i mentioned contain information required such as the Do you think i will be able to achieve this with the implementations you are suggesting as i have struggled in with normal xml parsers? If you are confident i will go and have another go, but i have tried so much! Thank you so much for your help. – docker dev Mar 29 '20 at 20:53
  • Absolutely - data in XML [attributes](https://www.w3schools.com/xml/xml_attributes.asp) can be extracted. JAXB is a good place to start. – andrewJames Mar 29 '20 at 20:59
  • @andrewjames I will take a look at that one now, thanks Andrew – docker dev Mar 29 '20 at 21:06
  • @andrewjames Just a quick update i had a look at JAXB and as my implementation is android i was pointed towards simplexml, i am trying to implement it however i am running into issues if you want to have a look i started a new question as i thought it better practice.https://stackoverflow.com/questions/60921409/android-simplexml-deserialisation – docker dev Mar 29 '20 at 22:16
  • A new question makes sense. I took a look at doing this task using SAX (fairly straightforward for the basic extraction), so if that ever looks like an option, I can help. But maybe not for Android (I don't develop for that platform). Good luck. – andrewJames Mar 30 '20 at 00:00

1 Answers1

0

You could just grow your own little parser for this particular task however getting use to an XML Parser would be a real good idea:

The Nodes Class (simple Nodes parser included in class):

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Nodes {

    private String node_ID;
    private double latitude;
    private double longitude;
    private String name;
    private String waypoint_Type;
    private int    level_ID;
    private String on_Starting_Route;
    private String on_Finish_Route;

    // Constructor #1
    public Nodes() { }

    // Constructor #2
    public Nodes(String nodeID, double latitude, double longitude, String name, 
                 String waypointType, int levelID, String startingRoute, 
                 String finishRoute) {
        this.node_ID = nodeID;
        this.latitude = latitude;
        this.longitude = longitude;
        this.name = name;
        this.waypoint_Type = waypointType;
        this.level_ID = levelID;
        this.on_Starting_Route = startingRoute;
        this.on_Finish_Route = finishRoute;
    }

    // Getters and Setters
    public String getNode_ID() {
        return node_ID;
    }

    public void setNode_ID(String node_ID) {
        this.node_ID = node_ID;
    }

    public double getLatitude() {
        return latitude;
    }

    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getWaypoint_Type() {
        return waypoint_Type;
    }

    public void setWaypoint_Type(String waypoint_Type) {
        this.waypoint_Type = waypoint_Type;
    }

    public int getLevel_ID() {
        return level_ID;
    }

    public void setLevel_ID(int level_ID) {
        this.level_ID = level_ID;
    }

    public String getOn_Starting_Route() {
        return on_Starting_Route;
    }

    public void setOn_Starting_Route(String on_Starting_Route) {
        this.on_Starting_Route = on_Starting_Route;
    }

    public String getOn_Finish_Route() {
        return on_Finish_Route;
    }

    public void setOn_Finish_Route(String on_Finish_Route) {
        this.on_Finish_Route = on_Finish_Route;
    }

    // Read in Nodes from XML (simple parser)
    public List<Nodes> getNodesFromFile(String filePath) {
        List<Nodes> nodes = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.equals("")) {
                    continue;
                }
                if (line.toLowerCase().startsWith("<node id=\"")) {
                    String nodeID;
                    double lat = 0.0d;
                    double lon = 0.0d;
                    String name = "";
                    String wayType = "";
                    int levID = 0;
                    String startR = "";
                    String finishR = "";

                    nodeID = line.substring("<node id=\"".length(), line.lastIndexOf("\">"));
                    int count = 0;
                    while ((line = reader.readLine()) != null) {
                        line = line.trim();
                        if (line.equalsIgnoreCase("</node>")) {
                            break;
                        }
                        if (line.equals("")) {
                            continue;
                        }
                        count++;
                        switch (count) {
                            case 1:
                                String la = line.substring((line.contains("<data key=\"lat\">")
                                        ? "<data key=\"lat\">".length() : "<data key=\"lat\"".length()),
                                        (line.contains("</data>") ? line.indexOf("</data>") : line.indexOf("/>")));
                                lat = (la.matches("-?\\d+(\\.\\d+)?") ? Double.parseDouble(la) : 0.0d);
                                break;
                            case 2:
                                String lg = line.substring((line.contains("<data key=\"lon\">")
                                        ? "<data key=\"lon\">".length() : "<data key=\"lon\"".length()),
                                        (line.contains("</data>") ? line.indexOf("</data>") : line.indexOf("/>")));
                                lon = (lg.matches("-?\\d+(\\.\\d+)?") ? Double.parseDouble(lg) : 0.0d);
                                break;
                            case 3:
                                String nm = line.substring((line.contains("<data key=\"name\">")
                                        ? "<data key=\"name\">".length() : "<data key=\"name\"".length()),
                                        (line.contains("</data>") ? line.indexOf("</data>") : line.indexOf("/>")));
                                name = nm.trim().equals("") ? "" : nm;
                                break;
                            case 4:
                                String wt = line.substring((line.contains("<data key=\"waypoint_type\">")
                                        ? "<data key=\"waypoint_type\">".length() : "<data key=\"waypoint_type\"".length()),
                                        (line.contains("</data>") ? line.indexOf("</data>") : line.indexOf("/>")));
                                wayType = wt.trim().equals("") ? "" : wt;
                                break;
                            case 5:
                                String lid = line.substring((line.contains("<data key=\"level_id\">")
                                         ? "<data key=\"level_id\">".length() : "<data key=\"level_id\"".length()),
                                         (line.contains("</data>") ? line.indexOf("</data>") : line.indexOf("/>")));

                                levID = (lid.matches("^-?\\d+$") ? Integer.parseInt(lid) : 0);
                                break;
                            case 6:
                                 String sr = line.substring((line.contains("<data key=\"on_starting_route\">")
                                        ? "<data key=\"on_starting_route\">".length() : "<data key=\"on_starting_route\"".length()),
                                        (line.contains("</data>") ? line.indexOf("</data>") : line.indexOf("/>")));
                                startR = sr.trim().equals("") ? "" : sr;
                                break;
                            case 7:
                                String fr = line.substring((line.contains("<data key=\"on_finish_route\">")
                                        ? "<data key=\"on_finish_route\">".length() : "<data key=\"on_finish_route\"".length()),
                                        (line.contains("</data>") ? line.indexOf("</data>") : line.indexOf("/>")));
                                finishR = fr.trim().equals("") ? "" : fr;
                                break;
                        }
                    }
                    nodes.add(new Nodes(nodeID, lat, lon, name, wayType, levID, startR, finishR));
                }
            }
        }
        catch (FileNotFoundException ex) {
            System.err.println(ex.getMessage());
        }
        catch (IOException ex) {
            System.err.println(ex.getMessage());
        }
        return nodes;
    }

    // The toString() method
    @Override
    public String toString() {
        return new StringBuffer("").append("Node ID = ").append(node_ID).append(", Latitude = ")
                .append(latitude).append(", Longitude = ").append(longitude).append(", Name = ")
                .append(name).append(", Waypoint Type = ").append(waypoint_Type).append(", Level ID = ")
                .append(level_ID).append(", On Starting Route = ").append(on_Starting_Route)
                .append(", On Finish Route = ").append(on_Finish_Route).toString();
    }

}

To Use The Nodes Class:

Here's how you might use this class:

Nodes n = new Nodes();
List<Nodes> nodes = n.getNodesFromFile("Graphml.xml");

// Display the Nodes in Console Window...
if (!nodes.isEmpty()) {
    for (Nodes node : nodes) {
        // System.out.println(node.toString());
        System.out.printf("%-20s %-15s%n", "Node ID:", node.getNode_ID());
        System.out.printf("%-20s %-15s%n", "Latitude:", node.getLatitude());
        System.out.printf("%-20s %-15s%n", "Longitude:", node.getLongitude());
        System.out.printf("%-20s %-15s%n", "Name:", node.getName());
        System.out.printf("%-20s %-15s%n", "Waypoint Type:", node.getWaypoint_Type());
        System.out.printf("%-20s %-15s%n", "Level ID:", node.getLevel_ID());
        System.out.printf("%-20s %-15s%n", "On Starting Route:", node.getOn_Starting_Route());
        System.out.printf("%-20s %-15s%n", "On Finish Route:", node.getOn_Finish_Route());
        System.out.println();
    }
}
DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22