Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Parsing text

Tags:

c#

parsing

I've tried searching for the answer but have not found the correct way of parsing this chunk of text:

<Hotspot X="-8892.787" Y="-121.9584" Z="82.04719" />
<Hotspot X="-8770.094" Y="-109.5561" Z="84.59527" />
<Hotspot X="-8755.385" Y="-175.0732" Z="85.12362" />
<Hotspot X="-8701.564" Y="-114.794" Z="89.48868" />
<Hotspot X="-8667.162" Y="-122.9766" Z="91.87251" />
<Hotspot X="-8802.135" Y="-111.0008" Z="82.53865" />  

I want to output each line into:

Ex. X="-8892.787" Y="-121.9584" etc...
like image 795
Anden Avatar asked Dec 13 '25 04:12

Anden


1 Answers

If you can possibly treat this as XML, that would be by far the better way, so, consider treating it as:

<Hotspots>
  <Hotspot X="-8892.787" Y="-121.9584" Z="82.04719" />
  <Hotspot X="-8770.094" Y="-109.5561" Z="84.59527" />
  <Hotspot X="-8755.385" Y="-175.0732" Z="85.12362" />
  <Hotspot X="-8701.564" Y="-114.794" Z="89.48868" />
  <Hotspot X="-8667.162" Y="-122.9766" Z="91.87251" />
  <Hotspot X="-8802.135" Y="-111.0008" Z="82.53865" />  
</Hotspots>

And loading it into an XmlDocument, then parsing it as follows:

var xml = "<Hotspots><Hotspot X=\"-8892.787\" Y=\"-121.9584\" Z=\"82.04719\" /></Hotspots>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

foreach (XmlNode item in doc.SelectNodes("/Hotspots/Hotspot"))
{
    Console.Write(item.Attributes["X"].Value);
    Console.Write(item.Attributes["Y"].Value);
    Console.Write(item.Attributes["Z"].Value);

    // And to get the ouput you're after:
    Console.Write("X=\"{0}\" Y=\"{1}\" Z=\"{2}\"", 
                  item.Attributes["X"].Value, 
                  item.Attributes["Y"].Value, 
                  item.Attributes["Z"].Value);
}

Note: I've used a reduced example in var xml = "..." to make it a bit more readable

like image 62
Rob Avatar answered Dec 14 '25 17:12

Rob