-2

Possible Duplicate:
Parsing XML String in C#

How to process the below XML file and store the element value in an array

  <UserID>
  <Total>2</Total>
  <X1>2</X1>
  <Y1>4</Y1>
  <Attached1>2,3,4</Attached1>
  <X2>7</X2>
  <Y2>8</Y2>
  <Attached2>4,5,6</Attached2>
  </UserID>

Here I need to parse the elements X1 and X2 and store them in the same array.

Similarly I need to parse the Elements for Y1, Y2 and Attached1, Attached2 and store them in the same array.

This file may grow or shrink dynamically.

We can have X1, X2 up to X100 elements or X1, X2, up to X10 elements.

I do not want it to be restricted to few elements.

Here Total element indicates that there can be two X elements like X1 and X2

If the value of total is 5 then there can be 5 X elements like X1, X2, X3, X4 and X5.

I need to parse and store the values dynamically.

Any help?

Community
  • 1
  • 1
Bhairav Gooli
  • 63
  • 2
  • 8

2 Answers2

1

Using XmlDocument.SelectNodes and XPath:

XmlDocument document = new XmlDocument();
document.LoadXml("yourFile");

List<string> first = (from XmlNode node in document.SelectNodes("//X1 | //X2") 
                     select node.Value).ToList();
List<string> second = (from XmlNode node in document.SelectNodes("//Y1|//Y2|//Attached1|//Attached2") 
                      select node.Value).ToList();
horgh
  • 17,918
  • 22
  • 68
  • 123
Ria
  • 10,237
  • 3
  • 33
  • 60
1

I just have to say, the design of the document is bad. You shouldn't name your elements to indicate their position. Just give them a single common name and add as many as you need.

With that said, in your case you can generate the names (assuming they will always be sequential).

var xmlStr = @"<UserID>
  <Total>2</Total>
  <X1>2</X1>
  <Y1>4</Y1>
  <Attached1>2,3,4</Attached1>
  <X2>7</X2>
  <Y2>8</Y2>
  <Attached2>4,5,6</Attached2>
</UserID>
";
var doc = XDocument.Parse(xmlStr);
var users =
    from user in doc.Descendants("UserID")
    let total = (int)user.Element("Total")
    select new
    {
        X = Enumerable.Range(1, total)
                      .Select(i => (int)user.Element("X" + i))
                      .ToArray(),
        Y = Enumerable.Range(1, total)
                      .Select(i => (int)user.Element("Y" + i))
                      .ToArray(),
        Attached = Enumerable.Range(1, total)
                             .Select(i => (string)user.Element("Attached" + i))
                             .ToArray(),
    };
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272