Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a string in c#

Suppose there is an xml file like below:

<Instances>
  <Bits = "16" XCoord = "64" YCoord = "64" ZCoord = "64" FileType="jpeg" Location="C:\Series1\Image1.jpg" ImageNumber = "1"/>
  <Bits = "16" XCoord = "64" YCoord = "64" ZCoord = "64" FileType="jpeg" Location="C:\Series1\Image2.jpg" ImageNumber = "2"/>
  <Bits = "16" XCoord = "64" YCoord = "64" ZCoord = "64" FileType="jpeg" Location="C:\Series1\Image3.jpg" ImageNumber = "3"/>
  <Bits = "16" XCoord = "64" YCoord = "64" ZCoord = "64" FileType="jpeg" Location="C:\Series1\Image4.jpg" ImageNumber = "4"/>
  <Bits = "16" XCoord = "64" YCoord = "64" ZCoord = "64" FileType="jpeg" Location="C:\Series1\Image5.jpg" ImageNumber = "5"/>
</Instances>

This xml file is read as a string and passed on to a function. This xml file has information about a particular image file. I want to extract the location of all the image files from this string. So whatever is value of "location" filed i need to collect all those value. What is the best way to achieve this in C#.

Thanks,

like image 929
Jay Avatar asked Nov 28 '22 12:11

Jay


2 Answers

Simplest way: parse it as XML (I'd suggest using LINQ to XML) and then extra the information using the XML API. There's no point in treating it as raw character data yourself.

Sample:

XElement root = XElement.Parse(text);
List<string> images = root.Elements("Bits")
                          .Select(x => (string) x.Attribute("Location"))
                          .ToList();

(That will give a null for any Bits element which didn't contain a Location attribute.)

like image 134
Jon Skeet Avatar answered Dec 19 '22 00:12

Jon Skeet


Take care, your structure here is not a valid XML for the XElement.Parse because your elements do not have a name, but only attributes.

A possible correct structure would be:

<Instances>
<Image Bits = "16" XCoord = "64" YCoord = "64" ZCoord = "64" FileType="jpeg" Location="C:\Series1\Image1.jpg" ImageNumber = "1" />
<Image Bits = "16" XCoord = "64" YCoord = "64" ZCoord = "64" FileType="jpeg" Location="C:\Series1\Image2.jpg" ImageNumber = "2" />
<Image Bits = "16" XCoord = "64" YCoord = "64" ZCoord = "64" FileType="jpeg" Location="C:\Series1\Image3.jpg" ImageNumber = "3" />
<Image Bits = "16" XCoord = "64" YCoord = "64" ZCoord = "64" FileType="jpeg" Location="C:\Series1\Image4.jpg" ImageNumber = "4" />
<Image Bits = "16" XCoord = "64" YCoord = "64" ZCoord = "64" FileType="jpeg" Location="C:\Series1\Image5.jpg" ImageNumber = "5" />
</Instances>

These would result in folowing C# Code for Parsing - based on Jon Skeet's code from above:

 XElement root = XElement.Parse(text);
 List<string> images = root.Elements("Image")
                           .Select(x => (string) x.Attribute("Location"))
                           .ToList();

HTH :)

like image 36
spookycoder Avatar answered Dec 19 '22 02:12

spookycoder