Time for action—Reading from the XML file

We are going to create a function to read from an XML file. So, let's proceed step by step.

  1. First, create the Layer class as follows:
    class Layer
    {
    public var id : String;
    public function new()
    {}
    }
    
  2. Now create the Page class as follows:
    class Page
    {
    public var name : String;
    public var layers : List<Layer>;
    public function new()
    {
    }
    }
    
  3. Now, let's create a function to create a page from an XML file. Add the following function to the Page class:
    public static function fromXMLFile(path : String) : Page
    {
    var nPage = new Page();
    var xmlDoc = Xml.parse(neko.io.File.read(path, false). readAll().toString());
    nPage.name = xmlDoc.firstElement().get("name");
    return nPage;
    }
    
  4. As you can see, it is not yet complete. We have to parse a layer from the XML file, so let's do it now. Add the following function in the Layer class:
    public static function fromXMLNode(node : Xml)
    {
    var nLayer : Layer;
    nLayer = new Layer();
    nLayer.id = node.get("id");
    return nLayer;
    }
    
  5. Now, in the fromXMLFile function, let's add some code to iterate over the nodes named layers, and parse them using the fromXMLNode function:
    public static function fromXMLFile(path : String) : Page
    {
    var nPage = new Page();
    var xmlDoc = Xml.parse(neko.io.File.read (path, false).readAll().toString());
    nPage.name = xmlDoc.firstElement().get("name");
    for(l in xmlDoc.firstElement().elementsNamed("layer"))
    {
    nPage.layers.add(Layer.fromXMLNode(l));
    }
    return nPage;
    }
    

What just happened?

As you see, we are simply expecting our document to respect the structure that we have defined; therefore, it was pretty easy to parse our XML file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.9.147