Anthony
Anthony

Reputation: 437

count number of "elements" in an XML tag using c#

I'm using C# in reading an XML file and counting how many "elements" there are in an XML tag, like this for example...

<Languages>English, Deutsche, Francais</Languages>

there are 3 "elements" inside the Languages tag: English, Deutsche, and Francais . I need to know how to count them and return the value of how much elements there are. The contents of the tag have the possibility of changing over time, because the XML file has to expand/accommodate additional languages (whenever needed).

IF this is not possible, please do suggest workarounds for the problem. Thank you.

EDIT: I haven't come up with the code to read the XML file, but I'm also interested in learning how to.

EDIT 2: revisions made to question

Upvotes: 0

Views: 3102

Answers (3)

Scott
Scott

Reputation: 13941

string xml = @"<Languages>English, Deutsche, Francais</Languages>";
var doc = XDocument.Parse(xml);

string languages = doc.Elements("Languages").FirstOrDefault().Value;
int count = languages.Split(',').Count();

In response to your edits which indicate that you're not simply trying to pull out comma separated strings from an XML element, then your approach to storing the XML in the first place is incorrect. As another poster commented, it should be:

<Languages>
    <Language>English</Language>
    <Language>Deutsche</Language>
    <Language>Francais</Language>
</Languages>

Then, to get the count of languages:

string xml = @"<Languages>
                   <Language>English</Language>
                   <Language>Deutsche</Language> 
                   <Language>Francais</Language>
               </Languages>";

var doc = XDocument.Parse(xml);

int count = doc.Element("Languages").Elements().Count();

Upvotes: 5

rbtLong
rbtLong

Reputation: 1582

Ok, but just to be clear, an XML Element has a very specific meaning. In fact, the entire codeblock you have is an XML Element.

XElement xElm = new XElement("Languages", "English, Deutsche, Francais");
string[] elements = xElm.Value.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727097

First, an "ideal" solution: do not put more than one piece of information in a single tag. Rather, put each language in its own tag, like this:

<Languages>
    <Language>English</Language>
    <Language>Deutsche</Language>
    <Language>Francais</Language>
</Languages>

If this is not possible, retrieve the content of the tag with multiple languages, split using allLanguages.Split(',', ' '), and obtain the count by checking the length of the resultant array.

Upvotes: 3

Related Questions