String parsing and generating JSON and XML structure.

Markus Freitag 3,786 Reputation points
2023-09-30T15:37:58.7666667+00:00

Hello!

I get this string and have to make

an XML structure and a JSON structure.

string received = "{s_name=length,s_value=240.000,s_unit=1.0mm};{s_name=width,s_value=152.000,s_unit=1.0mm};{s_name=thickness,s_value=1.600,s_unit=1.0mm};{s_name=speed,s_value=45,s_unit=1.0mm/s};{s_name=position_X",s_value=240.000,s_unit=1.0mm};{s_name=position_Y,s_value=240.000,s_unit=1.0mm}";

What is the best way to parse this? What is the best way to create an XML, JSON structure from the string? Which possibilities do I have?

Thanks!

<ROOT>
	<VALUES>
		<VALUE s_name="length"
		             s_value="240.000"
		             s_unit="1.0 mm"/>
		<VALUE s_name="width"
		             s_value="152.000"
		             s_unit="1.0 mm"/>
		<VALUE s_name="thickness"
		             s_value="1.600"
		             s_unit="1.0 mm"/>
		<VALUE s_name="speed"
		             s_value="45"
		             s_unit="1.0 mm/s"/>
		<VALUE s_name="position_X"
		             s_value="-10.000"
		             s_unit="1.0 mm"/>
		<VALUE s_name="position_Y"
		             s_value="162.000"
		             s_unit="1.0 mm"/>
	</VALUES>
</ROOT>

{
	"ROOT": {
		"VALUES": {
			"VALUE": [
				{
					"_s_name": "length",
					"_s_value": "240.000",
					"_s_unit": "1.0 mm"
				},
				{
					"_s_name": "width",
					"_s_value": "152.000",
					"_s_unit": "1.0 mm"
				},
				{
					"_s_name": "thickness",
					"_s_value": "1.600",
					"_s_unit": "1.0 mm"
				},
				{
					"_s_name": "speed",
					"_s_value": "45",
					"_s_unit": "1.0 mm/s"
				},
				{
					"_s_name": "position_X",
					"_s_value": "-10.000",
					"_s_unit": "1.0 mm"
				},
				{
					"_s_name": "position_Y",
					"_s_value": "162.000",
					"_s_unit": "1.0 mm"
				}
			]
		}
	}
}
// *** For XML, I think it is ok.

[XmlRoot(ElementName="VALUE")]
public class VALUE { 

	[XmlAttribute(AttributeName="s_name")] 
	public string SName { get; set; } 

	[XmlAttribute(AttributeName="s_value")] 
	public double SValue { get; set; } 

	[XmlAttribute(AttributeName="s_unit")] 
	public string SUnit { get; set; } 
}

[XmlRoot(ElementName="VALUES")]
public class VALUES { 

	[XmlElement(ElementName="VALUE")] 
	public List<VALUE> VALUE { get; set; } 
}

[XmlRoot(ElementName="ROOT")]
public class ROOT { 

	[XmlElement(ElementName="VALUES")] 
	public VALUES VALUES { get; set; } 
}


C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,381 questions
{count} votes

Accepted answer
  1. KOZ6.0 5,215 Reputation points
    2023-09-30T16:56:25.01+00:00

    There was something wrong with position_X so I fixed it. Is it like this?

    using System;
    using System.Collections.Generic;
    using System.Text.RegularExpressions;
    
    internal class Program
    {
        public class Item {
            public string s_name { get; set; }
            public double s_value { get; set; }
            public string s_unit { get; set; }
    
            public override string ToString() {
                return $"s_name={s_name},s_value={s_value},s_unit={s_unit}";
            }
        }
    
        static void Main(string[] args) {
            string received
                = "{s_name=length,s_value=240.000,s_unit=1.0mm};"
                + "{s_name=width,s_value=152.000,s_unit=1.0mm};"
                + "{s_name=thickness,s_value=1.600,s_unit=1.0mm};"
                + "{s_name=speed,s_value=45,s_unit=1.0mm/s};"
                + "{s_name=position_X,s_value=240.000,s_unit=1.0mm};"
                + "{s_name=position_Y,s_value=240.000,s_unit=1.0mm}";
    
            string pattern = 
              @"\{s_name=(\w+),s_value=([\d.]+),s_unit=([\d.]+[a-zA-Z/]+)\}";
            MatchCollection matches = Regex.Matches(received, pattern);
            List<Item> items = new List<Item>();
            foreach (Match match in matches) {
                Item item = new Item {
                    s_name = match.Groups[1].Value,
                    s_value = double.Parse(match.Groups[2].Value),
                    s_unit = match.Groups[3].Value
                };
                items.Add(item);
                Console.WriteLine($"{item}");
            }
            Console.ReadKey();
        }
    }
    

    The rest is up to you.

    1 person found this answer helpful.

4 additional answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 57,886 Reputation points
    2023-09-30T19:07:05.1+00:00

    Your sample is neither valid json or xml, so you need to write your own parser. You only show one sample, but it looks like you could split on semicolons then for each remove braces and split on commas, then for each of these items split on =. something like:

            var root = new ROOT
            {
                VALUES = new VALUES
                {
                    VALUE = received.Split(";")
                        .Select(r => r.Replace("{","").Replace("}",""))
                        .Select(r =>
                        {
                            var v = new VALUE();
                            var props = r.Split(',');
                            foreach (var prop in props)
                            {
                                var nv = prop.Split('='); 
                                switch (nv[0])
                                {
                                    case "s_name": v.SName = nv[1]; break;
                                    case "s_value": v.SValue = double.Parse(nv[1]); break;
                                    case "s_unit": v.SUnit = nv[1]; break;
                                }
                            }
                            return v;
                        })
                        .ToList()
                }
            };
            ```
    
    
    1 person found this answer helpful.

  2. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

  3. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

  4. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more