Victor
Victor

Reputation: 1108

How to get strings inside tags?

I have a webservice that returns this string value:

<NewDataSet>
  <Table>
    <Country>Mexico</Country>
    <City>Acapulco / G. Alvarez</City>
  </Table>
  <Table>
    <Country>Mexico</Country>
    <City>Aerop. Internacional Monterrey, N. L.</City>
  </Table>
  <Table>
    <Country>Mexico</Country>
    <City>Aguascalientes, Ags.</City>
  </Table>
</NewDataSet>

I need to insert the City values in a database table. What I intend to do is search the entire string and everytime it detects a tag , I want to extract the value inside and then I would store each value in a List for later use.

However I have not been able to find a way to repeat the process various times on the same string.

I first tried Substring and Split with no success yet. Do you know a method that help me solve this problem? Thanks in advance.

Upvotes: 0

Views: 134

Answers (2)

Ant P
Ant P

Reputation: 25231

Use XML parsing with Linq to XML or similar:

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

XElement stringAsXml = XElement.Parse(myString);

Upvotes: 0

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68707

var cities = XDocument.Parse(myString).Descendants("City").Select(d => d.Value);

This is an example of using LINQ to XML to get the value out. In general your problem is basically you have an XML string, which you need to somehow parse and get the appropriate values out. Some other common methods could have been to use XmlDocument or deserializing your XML to a class structure.

Upvotes: 2

Related Questions