OSMServer/Server/RegionConverter.cs
2023-03-30 18:25:12 +02:00

73 lines
2.3 KiB
C#

using System.Globalization;
using System.Xml;
using OSMDatastructure;
namespace Server;
public class RegionConverter
{
private static readonly XmlReaderSettings ReaderSettings = new()
{
IgnoreWhitespace = true,
IgnoreComments = true
};
private static readonly NumberFormatInfo decimalInfo = new()
{
NumberDecimalSeparator = "."
};
public static HashSet<Region> ImportXml(string filePath)
{
if (!File.Exists(filePath))
throw new FileNotFoundException();
Console.WriteLine("Getting highwayNodeIds...");
FileStream xmlFileStream = new FileStream(filePath, FileMode.Open);
Dictionary<ulong, ulong> nodeIdRegionDict = GetNodesAndRegions(XmlReader.Create(xmlFileStream, ReaderSettings));
xmlFileStream.Position = 0;
Console.WriteLine("Importing Nodes...");
Dictionary<ulong, OsmNode> nodes =
GetHighwayNodesFromIds(XmlReader.Create(xmlFileStream, ReaderSettings), requiredNodeIds);
requiredNodeIds.Clear();
xmlFileStream.Position = 0;
Console.WriteLine("Importing Ways...");
HashSet<OsmNode> retNodes = ConnectNodes(XmlReader.Create(xmlFileStream, ReaderSettings), nodes);
nodes.Clear();
return retNodes;
}
private static Dictionary<ulong, ulong> GetNodesAndRegions(XmlReader xmlReader)
{
bool isHighway = false;
while (xmlReader.ReadToFollowing("way"))
{
isHighway = false;
currentIds.Clear();
XmlReader wayReader = xmlReader.ReadSubtree();
while (wayReader.Read())
{
if (xmlReader.Name == "tag" && xmlReader.GetAttribute("k")!.Equals("highway"))
{
isHighway = true;
}
else if (xmlReader.Name == "nd")
{
try
{
currentIds.Add(Convert.ToUInt64(xmlReader.GetAttribute("ref")));
}
catch (FormatException) { };
}
}
if (isHighway)
{
retSet.UnionWith(currentIds);
}
wayReader.Close();
}
xmlReader.Close();
}
}