C # Text Analysis

I tried to find the answer, but did not find the correct way to parse this piece 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 to:

Ex. X="-8892.787" Y="-121.9584" etc...
+3
source share
3 answers

I assume that you are not too knowledgeable about your development skills, but this is not just text, but xml, and you can easily access it using Linq To XML in this way:

XDocument myXDoc = XDocument.Parse(string.Format("<?xml version=\"1.0\" encoding=\"utf-8\"?><root>{0}<root>", yourXmlString));
foreach (XElement hotspot in myXDoc.Root.Elements())
{
    Console.WriteLine(string.Format("X=\"{0}\" Y=\"{1}\"", hotspot.Attribute("X").Value, hotspot.Attribute("Y").Value));
}

I read XML and Linq To XML at:

http://msdn.microsoft.com/en-us/library/aa286548.aspx

http://msdn.microsoft.com/en-us/library/bb387098.aspx

+4
source

If you can treat this as XML, this will certainly be the best way, so consider 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 in XmlDocument, then parsing it like this:

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);
}

. var xml = "...", .

+9

, <Hotspot...

//Lines are read into (for this example) a string[] called lines
List<string> valueLines = new List<string>();

foreach(string l in lines)
{
  string x;
  string y;
  string z;

  int xStart = l.IndexOf("X");
  int yStart = l.IndexOf("Y");
  int zStart = l.IndexOf("Z");
  int closeTag = l.IndexOf(@"/");

  StringBuilder vlBuilder = new StringBuilder();

  vlBuilder.Append(l.Substring(xStart, (yStart - xStart - 1));
  vlBuilder.Append(l.Substring(yStart, (zStart - yStart - 1));
  vlBuilder.Append(l.Substring(zStart, (closeTag - zStart - 1));

  valueLines.Add(vlBuilder.ToString());
}
0

Source: https://habr.com/ru/post/1760809/


All Articles