Parsing GML for Unity using C# or JavaScript: A step-by-step guide

Looking to extract GML data and integrate it with Unity.
Below is my C# script for XML parsing:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Xml.Linq;
using System.Linq;
using UnityEngine.UI;

public class Manager_02 : MonoBehaviour 
{
  public GameObject text01;

  private void Start()
  {
    string path = @"C:unitySample.gml";

    XDocument xd = XDocument.Load(path);
    XNamespace gml = "http://www.opengis.net/gml";

    Text txt = GameObject.Find("Text").GetComponent<Text>();
    //this is for unity

    var query = xd.Descendants(gml + "coord")
        .Select(e => new
        {
            X = (decimal)e.Element(gml + "X"),
            Y = (decimal)e.Element(gml + "Y")
        });

    foreach (var c in query)
    {
      txt.text = c.ToString();
    }
  }
}

The script works perfectly with the first XML example:

<?xml version='1.0' encoding='UTF-8'?>
<schema xmlns='http://www.w3.org/2000/10/XMLSchema'
        xmlns:gml='http://www.opengis.net/gml'
        xmlns:xlink='http://www.w3.org/1999/xlink'
        xmlns:xsi='http://www.w3.org/2000/10/XMLSchema-instance'
        xsi:schemaLocation='http://www.opengis.net/gml/feature.xsd'>
  <gml:Polygon srsName='http://www.opengis.net/gml/srs/epsg.xml#4283'>
    <gml:outerBoundaryIs>
      <gml:LinearRing>
        <gml:coord>
          <gml:X>152.035953</gml:X>
          <gml:Y>-28.2103190007845</gml:Y>
        </gml:coord>
      </gml:LinearRing>
    </gml:outerBoundaryIs>
  </gml:Polygon>
</schema>

However, it encounters issues when trying to parse the second XML structure.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<IndoorFeatures xmlns="http://www.opengis.net/indoorgml/1.0/core"
                xmlns:gml="http://www.opengis.net/gml/3.2" 
                xmlns:ns4="http://www.opengis.net/indoorgml/1.0/navigation" 
                xmlns:xlink="http://www.w3.org/1999/xlink" 
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
                gml:id="IFs" xsi:schemaLocation="http://www.opengis.net/indoorgml/1.0/core http://schemas.opengis.net/indoorgml/1.0/indoorgmlcore.xsd">
    <gml:name>IFs</gml:name>
    <gml:boundedBy>
        <gml:Envelope srsDimension="3" srsName="EPSG::4326">
            <gml:lowerCorner>112.1168351477 48.8817891374 10.0</gml:lowerCorner>
            <gml:upperCorner>116.7830482115...

If you prefer a simpler approach, consider using code like this:

var query = xd.Descendants(gml + "LinearRing").Select(
    e => new
    {
        X = (decimal)e.Element(gml + "pos")
    }
);

A question arises: how can GML be parsed effectively in C# (or JavaScript) for Unity implementation?

Answer №1

Consider incorporating the following code snippet to address any namespace-related issues:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication65
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XElement indoorFeatures = doc.Root;

            XNamespace xsGml= indoorFeatures.GetNamespaceOfPrefix("gml");
            XNamespace ns = indoorFeatures.GetDefaultNamespace();

            var results = doc.Elements(ns + "IndoorFeatures").Select(x => new {
                name = (string)x.Element(xsGml + "name"),
                lowerCorner = (string)x.Descendants(xsGml +  "lowerCorner").FirstOrDefault(),
                upperCorner = (string)x.Descendants(xsGml + "upperCorner").FirstOrDefault(),
                primalSpaceFeatures = x.Descendants(ns + "PrimalSpaceFeatures").Select(y => new {
                    name = (string)y.Element(xsGml + "name"),
                    cellSpace = (string)y.Descendants(ns + "CellSpace").FirstOrDefault().Attribute(xsGml + "id"),
                    description = (string)y.Descendants(xsGml + "description").FirstOrDefault(),
                    cellSpaceName = (string)y.Descendants(ns + "CellSpace").FirstOrDefault().Element(xsGml + "name")
                }).ToList()
            }).FirstOrDefault();
        }
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting Date Format According to Visitor's Time Zone in VueJs/JS

I have a Date in string Format: 2020-07-13 7:07 AM (which is indian time). I am looking to adjust this time according to the browser's time zone, which could be either in the US or Africa. I have attempted various methods to convert it accurately. He ...

No matter what, the statement will always be false when this has the class 'has-success'

i am a beginner in jquery and i am looking to implement form validation in asp.net mvc. Currently, the validation is working for each field individually, but I want to disable the submit button until certain fields are correctly filled out. Even after fill ...

By employing the $watch method, the table disappears from the div element

I've integrated the isteven-multi-select directive for my multi-select dropdown functionality. By providing it with a list of thingsList, it generates a corresponding checkedList as I make selections. Initially, I used a button to confirm the selecti ...

Node.js throwing error due to incorrect format of bind parameters as an array

I have been working with Nodejs/express and trying to implement a paramerized query in my API. However, I encountered the following error message in my console: Bind parameters must be array if namedPlaceholders parameter is not enabled Below is a snippet ...

Experiencing issues with retrieving data from an array returned by Django Rest Framework using AJAX, as it is showing as 'undefined'

I am facing an issue while trying to retrieve data from an array returned by an AJAX GET Request to Django Rest Framework. Despite console logging the data and identifying my target using index numbers, I keep encountering the undefined error. Even attempt ...

Combining multiple JSON Array values into one column in a CSV file

Looking at a JSON file structure like this: { "id": 2, "name": "I.1.A.2", "activeFlag": true, "recipients": [ { "id": 3, ...

What is the process for automatically activating the Enter key once moving to the next text input field?

Hey everyone, I am looking for a way to automatically trigger the enter button after the user switches to another HTML input type='text'. This is necessary for form validation. Below is the code snippet: <input type="text" class="form-contro ...

I'm curious about utilizing jsviews in conjunction with jquery sortable

Check out my jsFiddle Example where I am using jsViews in conjunction with JQuery sortable. By default, the remove function works fine; however, when you change the order of items and then try to delete one, multiple items are removed. How can this issue ...

What is the best way to assign the value of a specific key in one array as the key in a different array?

I am attempting to retrieve the value feature_1 associated with the key name from the array data. I then aim to set feature_1 as the key of another array asset, with an array as its corresponding value. For example: //input: data: { name: "feature_1" ...

Showing a collection of objects in a React component

**Recently started learning React and Node, and decided to fetch data into a functional component by following various tutorials. I successfully set up the server, connected it to the database, and fetched the data in React as per the tutorial instruction ...

React does not allow functions as child elements. I have thoroughly reviewed my code and cannot identify the source of this issue

I have a parent component with a lot of logic and several other components that are functional components with only the return JSX method. I kept getting a lot of "Functions are not valid as a React child" errors, so I made some changes to fix this. I thou ...

hover effect with fading transition while mouse is still hovering

Is there a way to create a fade-in/fade-out effect on a div without the mouse needing to leave the area? Let me provide a clearer explanation: When the mouse enters the object The object gradually fades in Then, after a delay, the object fades out while ...

The function was activated twice

Currently, I am facing an issue with my Node.js class where a function inside the class triggers the console.log statement twice. class Client{ constructor(){ this.test(); } test(){ console.log("testing"); } } var RR = n ...

AngularJS is throwing a TypeError because it cannot access the '0' property of an undefined value

for ( var i = 0; i < members.length; i++ ) { var value = value[i]; console.log(value); } Feeling really bewildered by how this could be incorrect... 'i' is set to zero, so it's perplexing how the value couldn' ...

FireFox is unable to input keystrokes into the date picker

Encountering an issue with running automation tests in Firefox while using selenium webdriver in c#. The problem arises specifically when trying to use the sendkeys function in Firefox, unlike Chrome where it runs smoothly. Below are the details of the ele ...

Choose an option from the dropdown menu when clicking on the radio button

My issue involves a drop-down menu along with two radio buttons, each with two values: jQuery('input[type=radio][name=radio_type]').change(function(e) { var value = jQuery(e.target.value); jQuery('select[name="optType"] option:selecte ...

Ways to retrieve a converted document using the Microsoft Graph API

I'm encountering an issue when trying to save a PDF file received from the Microsoft Graph API. The call I am making looks like this: const convertConfig = { headers: { Authorization: <my token> } }; convertConfig.headers['C ...

Does anyone know how to disable JavaScript on a webpage specifically for a Blackberry 8300 browser?

I am facing an issue with my JavaScript on the BlackBerry 8300, where the page renders differently when JavaScript is disabled. I would like to find a way to make sure that the "JavaScript disabled" version of the page appears for users using BlackBerry 83 ...

Passport is implementing multistrategies for multiple authentications simultaneously

After configuring Passport.js to utilize multiple strategies, I encountered an issue: passport.authenticate(['bearer', 'facebook-token', 'google-token', 'linkedin-token'],function(err, user, info) ... Although it i ...

Creating a flexible solution to include a textbox within a databound checkboxlist in C# using .NET

I am working on a .net web application with a C# backend and SQL Server data layer. In my project, I have an ASP:CheckBoxList that is populated using a stored procedure through direct data binding: ASP.net <asp:CheckBoxList ID="cblMyPlans" runat="serv ...