-3

My givens are

int random = 3;
string xml = "<Numbers> <Num>1</Num> <Num>2</Num> <Num>3</Num> <Num>4</Num><Num>5</Num> </Numbers>";

I want to iterate through this string and find if random is a number between <Num></Num>. Is there a way of doing this in C# Visual Studio?

Blah Blah
  • 49
  • 1
  • 8

4 Answers4

0

There are plenty of ways to do it, the simplest would probably be to use IndexOf:

if(xml.IndexOf("<Num>"+ random.ToString() + "</Num>") > -1)
{
    // found it!
}
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
0

Parse your XML to an XElement and query the numbers to a list:

var numList = XElement.Parse(xml)
    .Elements("Num")
    .Select(x => (int) x)
    .ToList();

And then check if your random number is in that list:

numList.Contains(random);

See this fiddle for a demo.

Charles Mager
  • 25,735
  • 2
  • 35
  • 45
0

With XDocument you can easily query and check if the numbers exist in your XML.

  // XML content
  string xml = "<Numbers>" +
                  "<Num>1</Num>" +
                   "<Num>2</Num>" +
                   "<Num>3</Num>" +
                   "<Num>4</Num>" +
                   "<Num>5</Num>" +
                "</Numbers>";

load string into XDocument. If you read from file use XDocument.Load(pathname) instead.

  var doc = XDocument.Parse(xml);

check if the random number exists.

  1. Take all elements from Numbers

  2. Select the value inside it

  3. Convert the results to string array

  4. Check if the array contains the random number

    int random = 3;
    bool exists = doc.XPathSelectElement("Numbers")
      .Elements()
      .Select(x => x.Value)
      .ToArray()
      .Contains(random.ToString());
    

Make sure to include those namespaces

     using System.Xml.Linq;
     using System.Xml.XPath;
Graham
  • 7,431
  • 18
  • 59
  • 84
Timon Post
  • 2,779
  • 1
  • 17
  • 32
-1

In this link you got an easy way to read through an XML: https://msdn.microsoft.com/es-es/library/cc189056(v=vs.95).aspx

If you just need that specific value you can stick with Zohar Peled's answer.

Zalomon
  • 553
  • 4
  • 14