CryptoSys Home > xmlsq > Use the count to query each matching element

Use the count to query each matching element


Iterate using result of count in cmd console

Input file: file.xml
<a>
  <b lang="en">Hello world</b>
  <b lang="fr">Bonjour le monde</b>
  <b lang="" />
</a>
> xmlsq -f //b file.xml
<b lang="en">Hello world</b>
<b lang="fr">Bonjour le monde</b>
<b lang="" />

> for /f %c in ('xmlsq --count //b file.xml') do set COUNT=%c

> echo %COUNT%
3

> for /L %i in (1,1,%COUNT%) do @xmlsq --delim ' (//b)[%i] file.xml
'Hello world'
'Bonjour le monde'
''

C# example

Input file: bookstore.xml
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book>
  <title lang="en">Harry Potter</title>
  <price>29.99</price>
</book>

<book>
  <title lang="en">Learning XML</title>
  <price>39.95</price>
</book>

<book>
  <title lang="es">El criticón</title>
  <price>19.95</price>
</book>
</bookstore>
C# code:
int n;
string s, query;
string xmlfile;

Console.WriteLine("\nUSE THE COUNT TO QUERY EACH MATCHING ELEMENT...");

xmlfile = "bookstore.xml";
Console.WriteLine("FILE: {0}", xmlfile);

Console.WriteLine("Use the count to query each matching element in turn...");
query = "//title";
n = Xmlsq.Query.Count(xmlfile, query);
Console.WriteLine("COUNT: Query: {0}", query);
Console.WriteLine(n);

for (int i = 1; i <= n; i++) {
	// Compose query
	query = string.Format("(//title)[{0}]", i);
	Console.WriteLine("Query: {0}", query);
	// then use it
	s = Query.GetText(xmlfile, query, Query.Opts.Asciify);
	Console.WriteLine(s);
}
Output:
USE THE COUNT TO QUERY EACH MATCHING ELEMENT...
FILE: bookstore.xml
Use the count to query each matching element in turn...
COUNT: Query: //title
3
Query: (//title)[1]
Harry Potter
Query: (//title)[2]
Learning XML
Query: (//title)[3]
El critic&#xF3;n

Contact us

To contact us or comment on this page, please send us a message.

This page last updated 2 June 2020

[Go to top]