I am trying to read variety type of XML files and in each xml type, root name and all other tags may change. I need to list all the xml tags but I couldnt succeed to read.
this is one of xml types.
<?xml version="1.0" encoding="ISO-8859-9"?>
<ITEMS>
<ITEM DBOP="INS" >
<CARD_TYPE>11</CARD_TYPE>
<CODE>MALZ1</CODE>
<NAME>MALZ1</NAME>
</ITEM>
</ITEMS>
and there is another one
<?xml version="1.0" encoding="ISO-8859-9"?>
<CLCARDS>
<CLCARD DBOP="INS" >
<CARD_TYPE>11</CARD_TYPE>
<CODE>CLCARD1</CODE>
<NAME>CLCARD1</NAME>
</CLCARD>
</CLCARDS>
I tried the code below but it didnt list all
string xml = txtXml.Text;
XDocument xdoc = XDocument.Parse(xml);
txtResult.Text = xdoc.Root.Name.ToString() + Environment.NewLine;
foreach (XElement element in xdoc.Elements())
txtResult.Text += element.Name.ToString() + Environment.NewLine;
it just listed the tags below for the first xml
items
items
I want to list it like below
items
item
card_type
code
name
how can I get such a result with LINQ?
Well, you can get all elements using the Descendants()
method:
foreach (var element in xdoc.Descendants())
{
Console.WriteLine(element.Name);
}
However, that won't do any indentation. If you want indentation as well, you could use something like:
public static int GetDepth(XElement element)
{
return element.Ancestors().Count();
}
Then:
foreach (var element in xdoc.Descendants())
{
Console.WriteLine("{0}{1}",
new string(' ', GetDepth(element)),
element.Name);
}
See more on this question at Stackoverflow