Sss
Sss

Reputation: 1529

c# How to know the root and child node names dynamically in xml in silverlight

I have xml stored in a string suppose like this:

String xmlString =
<A>
  <B>
     <C>C1</C>
     <D>D1</D>  
  </B>
  <Separator>S1</Separator>
  <B>
     <C>C2</C>
     <D>D2</D>
  </B> 
</A>

I wann know the name of each child node names from c# code.

I mean i will not have xml code it will come randomly to me so i don't know what is the xml structure and i wanna know all the child node names like A,B,Cand D here.

I mean i want to have something like which starts from the head/Parent( in lmy xml) and ends at the last(I mean in my xml) and prints one by one all the node like A,B,C,D,Separator, then again B ,C,D.

What i tried is this :

         IEnumerable<XElement> de = from el in xmlstring.Descendants() select el;
         foreach (XElement el in de)
         {
             Debug.WriteLine(el.Name);
         }

but it gives error :

Error   1   The type 'char' cannot be used as type parameter 'T' in the generic type or method 'System.Xml.Linq.Extensions.Descendants<T>(System.Collections.Generic.IEnumerable<T>)'. There is no boxing conversion from 'char' to 'System.Xml.Linq.XContainer'.   
Error   2   Could not find an implementation of the query pattern for source type 'System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>'.  'Select' not found.  Are you missing a reference or a using directive for 'System.Linq'? 

Both the error corresponds to xmlstring.Descendants() with red underline by Visual studio.

I HAVE THE FOLLOWING REFERENCES: (i amean i already have required refernces like Linq,xml etc.):

enter image description here Note: I am working in silverlight and i have to write this code in c#.

Thanks would be a big help.

Upvotes: 0

Views: 1723

Answers (1)

Asad Ali
Asad Ali

Reputation: 684

I can't comment yet so i'm gonna write here: System.Xml.Linq is what you need for XmlDocument.Descendants, not System.Linq.

Get All node name in xml in silverlight

^That is what you're looking for. I used this code and it printed the node names just fine.

    string xml = "<A><B><C>C1</C><D>D1</D></B><Separator>S1</Separator><B><C>C2</C><D>D2</D></B></A>";
    XDocument doc = XDocument.Parse(xml);
    foreach (XElement child in doc.Root.DescendantsAndSelf())
    {
        Console.WriteLine(child.Name.LocalName);
    }

Upvotes: 1

Related Questions