-1

I'm receiving some Cursor on Target data via UDP packets in a windows form, and I wanna use certain elements from it like the value of speed, course, lat, lon etc., but I'm struggling to find a good solution for this.

This is the string coming in:

<event how="m-i" time="2020-04-06T07:23:07.00Z" start="2020-04-06T07:23:07.00Z" stale="2020-04-06T07:23:22.00Z" version="2.0" type="a-f-A-M-F-Q" uid="ACRFT_TEST.00052">
  <point lat="55.6058278913" lon="8.4713637745" hae="53.968786" ce="16" le="12" />
  <detail>
    <track version="0.1" course="63.426428" speed="1.72" slope="-0.18" />
  </detail>
</event>

In this example I wanna use the value of "speed", but the number of digits following the speed=" is varying depending on the actual speed so i can't just use x number of characters after speed=".

So the best way would be to search the string for speed=" and then use all the characters after that, until the next ", so the output would be 1.72 (maybe using REGEX?) but so far, I have failed to accomplish this.

Can anyone help me out on this one?

  • 1
    [Parsing HTML with regex is a hard job](https://stackoverflow.com/a/4234491/372239) HTML and regex are not good friends. Use a parser, it is simpler, faster and much more maintainable. – Toto May 10 '20 at 10:31

2 Answers2

0

You can use the XmlReader. It is quite easy to use and small room for mistakes.

 XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreWhitespace = true;

            using (var fileStream = File.OpenText("XMLFile.xml"))
            using (XmlReader reader = XmlReader.Create(fileStream, settings))
            {
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element
                        && reader.Name == "track")
                    {
                        var speed = reader.GetAttribute("speed");
                        Console.WriteLine(speed);
                    }
                }
            }

This way you can always be sure that you read the right value. OBS in the example above I copied the xml you provided in a file to test it, you can read it directly.

Stelios Giakoumidis
  • 1,670
  • 1
  • 3
  • 16
0

Regex isn't meant for parsing XML data, use appropriate tools instead.

Just use XDocument class from System.Xml.Linq namspace:

XDocument xml = XDocument.Load("pass here stream with your xml data, it can be xml file URI");
xml.Descendants("track").Attributes("speed").First().Value
Michał Turczyn
  • 28,428
  • 14
  • 36
  • 58
  • This seems like a much smoother way of doing it!! Once I receive the packet it is stored as a string and i can't "XDocument.Load" a String. At least that's what Visual studio is saying. It works if i save the string as an XML file first, but it seems like an unnecessary step. Do you know how to use the string directly with XDocument? – Morten Bøttcher Nørgaard May 10 '20 at 18:40