/// <summary> /// Compile a query supplied as a Stream. /// </summary> /// <remarks> /// <para>The XQuery processor attempts to deduce the encoding of the query /// by looking for a byte-order-mark, or if none is present, by looking /// for the encoding declaration in the XQuery version declaration. /// For this to work, the stream must have the <c>CanSeek</c> property. /// If no encoding information is present, UTF-8 is assumed.</para> /// <para>The base URI of the query is set to the value of the <c>BaseUri</c> /// property. If this has not been set, then the base URI will be undefined, which /// means that any use of an expression that depends on the base URI will cause /// an error.</para> /// </remarks> /// <example> /// <code> /// XQueryExecutable q = compiler.Compile(new FileStream("input.xq", FileMode.Open, FileAccess.Read)); /// </code> /// </example> /// <param name="query">A stream containing the source text of the query</param> /// <returns>An <c>XQueryExecutable</c> which represents the compiled query object. /// The XQueryExecutable may be run as many times as required, in the same or a different /// thread. The <c>XQueryExecutable</c> is not affected by any changes made to the <c>XQueryCompiler</c> /// once it has been compiled.</returns> /// <exception cref="StaticError">Throws a StaticError if errors were detected /// during static analysis of the query. Details of the errors will be added as StaticError /// objects to the ErrorList if supplied; otherwise they will be written to the standard /// error stream. The exception that is returned is merely a summary indicating the /// status.</exception> public XQueryExecutable Compile(Stream query) { try { XQueryExpression exp = env.compileQuery(new DotNetInputStream(query), null); return(new XQueryExecutable(exp)); } catch (JXPathException e) { throw new StaticError(e); } }
/// <summary> /// Compile a query supplied as a String. /// </summary> /// <remarks> /// Using this method the query processor is provided with a string of Unicode /// characters, so no decoding is necessary. Any encoding information present in the /// version declaration is therefore ignored. /// </remarks> /// <example> /// <code> /// XQueryExecutable q = compiler.Compile("distinct-values(//*/node-name()"); /// </code> /// </example> /// <param name="query">A string containing the source text of the query</param> /// <returns>An <c>XQueryExecutable</c> which represents the compiled query object. /// The XQueryExecutable may be run as many times as required, in the same or a different /// thread. The <c>XQueryExecutable</c> is not affected by any changes made to the <c>XQueryCompiler</c> /// once it has been compiled.</returns> /// <exception cref="StaticError">Throws a StaticError if errors were detected /// during static analysis of the query. Details of the errors will be added as StaticError /// objects to the ErrorList if supplied; otherwise they will be written to the standard /// error stream. The exception that is returned is merely a summary indicating the /// status.</exception> public XQueryExecutable Compile(String query) { try { XQueryExpression exp = env.compileQuery(query); return(new XQueryExecutable(exp)); } catch (JXPathException e) { throw new StaticError(e); } }
/// <summary> /// will query an xml document given the document name and query or a query file name /// </summary> /// <param name="fileName"></param> /// <param name="query"></param> /// <returns></returns> private XmlDocument xmlQuery(string fileName, string query) { XmlDocument xmlResults = new XmlDocument(); try { fileName = "Config\\" + fileName; // create the collection XQueryNavigatorCollection col = new XQueryNavigatorCollection(); // add the file to the collection // the file will be referenced in the query statement by its alias col.AddNavigator(fileName, "theFile"); // if(fileName == "Config\\media.xml") // { // col.AddNavigator("Config\\fileTypes.xml", "fileTypes"); // } // copy the query out from the file String q = String.Empty; if (query.IndexOf(".xqu") > 0) //this is a query file { StreamReader sr = new StreamReader("XQu\\" + query); q = sr.ReadToEnd(); sr.Close(); } else { q = query; } // EventLog.WriteEntry("sctv",q.ToString()); // compile the query XQueryExpression expr = new XQueryExpression(q); xmlResults.LoadXml("<results>" + expr.Execute(col).ToXml() + "</results>"); // foreach(XmlNode node in xmlResults) // { // foreach(XmlElement elem in node) // { // lblMessage.Text += elem["Name"].InnerText.ToString(); // } // } } catch (Exception e) { // lblMessage.Text = e.ToString(); EventLog.WriteEntry("sctv", "File: " + fileName + " " + e.ToString()); } // EventLog.WriteEntry("sctv","Results: "+ expr.Execute(col).ToXml().ToString()); return(xmlResults); }
public void Evaluate(int SpreadMax) { if (this.FPinInput.PinIsChanged || this.FPinInQuery.PinIsChanged || this.FPinInAlias.PinIsChanged) { this.FPinOutIsValid.SliceCount = SpreadMax; this.FPinOutput.SliceCount = SpreadMax; for (int i = 0; i < SpreadMax; i++) { string input, query, alias; this.FPinInput.GetString(i, out input); this.FPinInAlias.GetString(i, out alias); this.FPinInQuery.GetString(i, out query); if (input == null) { input = String.Empty; } if (alias == null) { alias = String.Empty; } if (query == null) { query = String.Empty; } try { XQueryNavigatorCollection col = new XQueryNavigatorCollection(); XmlDocument doc = new XmlDocument(); doc.LoadXml(input); col.AddNavigator(doc.CreateNavigator(), alias); XQueryExpression expr = new XQueryExpression(query); string result = expr.Execute(col).ToXml(); this.FPinOutput.SetString(i, result); this.FPinOutIsValid.SetValue(i, 1); } catch { this.FPinOutput.SetString(i, ""); this.FPinOutIsValid.SetValue(i, 0); } } } }
private void Button_Click(object sender, RoutedEventArgs e) { try { XQueryNavigatorCollection col = new XQueryNavigatorCollection(); col.AddNavigator(_document.Navigator, "doc"); string query = _edtXQuery.Text; XQueryExpression xepr = new XQueryExpression(query); _edtResult.Text = xepr.Execute(col).ToXml(); } catch (Exception ex) { _edtResult.Text = ex.ToString(); _edtResult.Text += "\n\n"; _edtResult.Text += _edtXQuery.Text; } }
static void Main(string[] args) { XQueryNavigatorCollection col = new XQueryNavigatorCollection(); col.AddNavigator("C:\\Users\\matea\\workspace\\test\\my-file.xml", "doc"); string query = "for $x in document(\"doc\")/dsKurs/KursZbir return (<p>{$x/Oznaka/text(), \" \", $x/Nomin/text(), \" \", $x/Sreden/text()}</p>)"; XQueryExpression xepr = new XQueryExpression(query); string result = xepr.Execute(col).ToXml(); String html = "<html>" + result + "</html>"; using (FileStream fs = new FileStream("D:\\test.htm", FileMode.Create)) { using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8)) { w.WriteLine(html); } } Console.Write(result); Console.ReadKey(); }
// internal constructor internal XQueryEvaluator(XQueryExpression exp) { this.exp = exp; this.context = new DynamicQueryContext(exp.getStaticContext().getConfiguration()); }
// internal constructor internal XQueryExecutable(XQueryExpression exp) { this.exp = exp; }
/// <summary> /// Runs the solutions to all problems /// </summary> public static void Main() { XmlDocument doc = new XmlDocument(); doc.Load(PathToXmlFile); XmlNode root = doc.DocumentElement ?? doc.CreateElement("root"); // Problem 2: Write program that extracts all different artists which are found in the catalog.xml. // For each author you should print the number of albums in the catalogue. // Use the DOM parser and a hash - table. PrintNumbersOfAlbumsForEachArtist(root); // Problem 3: Implement the previous using XPath. PrintArtistsNumberOfAlbumsUsingXPath(root); // Problem 4: Using the DOM parser write a program to delete from catalog.xml all albums having price > 20. DeleteAlbumsByPrice(root, 20.0); // Check that albums are deleted: PrintNumbersOfAlbumsForEachArtist(root); // Problem 5: Write a program, which using XmlReader extracts all song titles from catalog.xml. var songTitles = ExtractSongTitlesFromCatalogue(PathToXmlFile); Console.WriteLine("Song titles: " + string.Join(", ", (songTitles as List <string>).ToArray())); // Problem 6: Rewrite the same using XDocument and LINQ query. XDocument xDoc = XDocument.Load(PathToXmlFile); var songTitlesUsingLinq = from songs in xDoc.Descendants("title") select songs.Value.Trim(); Console.WriteLine("Song titles (using LINQ): " + string.Join(", ", songTitlesUsingLinq)); // Problem 7: In a text file we are given the name, address and phone number of given person (each at a single line). // Write a program, which creates new XML document, which contains these data in structured XML format. CreateXmlPhonebook("../../phonebook.txt"); // Problem 8: Write a program, which (using XmlReader and XmlWriter) reads the file catalog.xml and creates the file album.xml, // in which stores in appropriate way the names of all albums and their authors. CreateAlbumsXml(PathToXmlFile); // Problem 9: Write a program to traverse given directory and write to a XML file its contents together with all subdirectories and files. // Use tags < file > and < dir > with appropriate attributes. // For the generation of the XML document use the class XmlWriter. using (var writer = new XmlTextWriter("../../traverseWithXmlWriter.xml", Encoding.UTF8)) { writer.WriteStartDocument(); writer.WriteStartElement("DirectoriesRoot"); CreateFileSystemXmlTreeUsingXmlWriter("../../..", writer); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); } // Problem 10: Rewrite the last exercises using XDocument, XElement and XAttribute. var xDocument = new XDocument(); xDocument.Add(CreateFileSystemXmlTree("../../../")); xDocument.Save("../../traverseWithXElement.xml"); // Problem 11: Write a program, which extract from the file catalog.xml the prices for all albums, published 5 years ago or earlier. // Use XPath query. doc.Load(PathToXmlFile); root = doc.DocumentElement; // returns all (no albums in the catalogue are newer...) var oldAlbumsPrices = root.SelectNodes("album/price[../year/text() < 2010]"); //// var oldAlbumsPrices = root.SelectNodes("album/price[../year/text() < 1980]"); // returns 2 albums' prices Console.WriteLine(new string('-', 50)); Console.WriteLine("Prices of the albums, published before 2010: "); foreach (var price in oldAlbumsPrices) { Console.WriteLine((price as XmlElement).InnerXml.Trim()); } // Problem 12: Rewrite the previous using LINQ query. Console.WriteLine(new string('-', 50)); Console.WriteLine("Prices of the albums, published before 2010 (using LINQ): "); var oldAlbumsPricesUsingLinq = from album in xDoc.Descendants("album") where int.Parse(album.Element("year").Value) < 2010 select album.Descendants("price").FirstOrDefault(); foreach (var price in oldAlbumsPricesUsingLinq) { Console.WriteLine(price.Value.Trim()); } // Problem 13: Create an XSL stylesheet, which transforms the file catalog.xml into HTML document, // formatted for viewing in a standard Web-browser. // Problem 14: Write a C# program to apply the XSLT stylesheet transformation on the file catalog.xml // using the class XslTransform. XslCompiledTransform catalogueXslt = new XslCompiledTransform(); catalogueXslt.Load("../../catalogue.xslt"); catalogueXslt.Transform(PathToXmlFile, "../../catalogue.html"); // Problem 15: // *Read some tutorial about the XQuery language. // Implement the XML to HTML transformation with XQuery (instead of XSLT). // Download some open source XQuery library for .NET and execute the XQuery to transform the catalog.xml to HTML. XQueryNavigatorCollection col = new XQueryNavigatorCollection(); // Add the XML document catalogue.xml to the collection using cat as the name to reference. col.AddNavigator("../../catalogue.xml", "cat"); var expr = new XQueryExpression( "<html><body><head><title>Catalogue</title></head>" + "<h1>Catalogue generated using XQuery</h1>" + "{For $a IN document(\"cat\")/catalogue/album " + "RETURN <div><strong>Title:</strong> {$a/name/text()}<br />" + "<strong>Artist:</strong> {$a/artist/text()}<br />" + "<strong>Year:</strong> {$a/year/text()}<br />" + "<strong>Producer:</strong> {$a/producer/text()}<br />" + "<strong>Price:</strong> {$a/price/text()}<br />" + "<strong>Songs:</strong><ol>{For $s IN $a/songs/song RETURN <li>{$s/title/text()}</li>}</ol>" + "</div><hr />}</body></html>"); StreamWriter str = new StreamWriter("../../catalogueUsingXQuery.html"); XQueryNavigator nav = expr.Execute(col); nav.ToXml(str); str.Close(); // Problem 16: // Using Visual Studio generate an XSD schema for the file catalog.xml. // Write a C# program that takes an XML file and an XSD file (schema) and validates the XML file against the schema. // Test it with valid XML catalogs and invalid XML catalogs. string xsdMarkup = File.ReadAllText("../../catalogue.xsd"); XmlSchemaSet schemas = new XmlSchemaSet(); schemas.Add(string.Empty, XmlReader.Create(new StringReader(xsdMarkup))); XDocument valid = XDocument.Load(PathToXmlFile); XDocument invalid = new XDocument( new XElement( "Root", new XElement("Child1", "content1"), new XElement("Child2", "content2"))); Console.WriteLine(new string('-', 50)); Console.WriteLine("Validating valid document:"); bool errors = false; valid.Validate(schemas, (o, e) => { Console.WriteLine("{0}", e.Message); errors = true; }); Console.WriteLine("Valid {0}", errors ? "did not validate" : "validated"); Console.WriteLine(); Console.WriteLine("Validating invalid document:"); errors = false; invalid.Validate(schemas, (o, e) => { Console.WriteLine("{0}", e.Message); errors = true; }); Console.WriteLine("doc2 {0}", errors ? "did not validate" : "validated"); }
/// <summary> /// Runs the solutions to all problems /// </summary> public static void Main() { XmlDocument doc = new XmlDocument(); doc.Load(PathToXmlFile); XmlNode root = doc.DocumentElement ?? doc.CreateElement("root"); // Problem 2: Write program that extracts all different artists which are found in the catalog.xml. // For each author you should print the number of albums in the catalogue. // Use the DOM parser and a hash - table. PrintNumbersOfAlbumsForEachArtist(root); // Problem 3: Implement the previous using XPath. PrintArtistsNumberOfAlbumsUsingXPath(root); // Problem 4: Using the DOM parser write a program to delete from catalog.xml all albums having price > 20. DeleteAlbumsByPrice(root, 20.0); // Check that albums are deleted: PrintNumbersOfAlbumsForEachArtist(root); // Problem 5: Write a program, which using XmlReader extracts all song titles from catalog.xml. var songTitles = ExtractSongTitlesFromCatalogue(PathToXmlFile); Console.WriteLine("Song titles: " + string.Join(", ", (songTitles as List<string>).ToArray())); // Problem 6: Rewrite the same using XDocument and LINQ query. XDocument xDoc = XDocument.Load(PathToXmlFile); var songTitlesUsingLinq = from songs in xDoc.Descendants("title") select songs.Value.Trim(); Console.WriteLine("Song titles (using LINQ): " + string.Join(", ", songTitlesUsingLinq)); // Problem 7: In a text file we are given the name, address and phone number of given person (each at a single line). // Write a program, which creates new XML document, which contains these data in structured XML format. CreateXmlPhonebook("../../phonebook.txt"); // Problem 8: Write a program, which (using XmlReader and XmlWriter) reads the file catalog.xml and creates the file album.xml, // in which stores in appropriate way the names of all albums and their authors. CreateAlbumsXml(PathToXmlFile); // Problem 9: Write a program to traverse given directory and write to a XML file its contents together with all subdirectories and files. // Use tags < file > and < dir > with appropriate attributes. // For the generation of the XML document use the class XmlWriter. using (var writer = new XmlTextWriter("../../traverseWithXmlWriter.xml", Encoding.UTF8)) { writer.WriteStartDocument(); writer.WriteStartElement("DirectoriesRoot"); CreateFileSystemXmlTreeUsingXmlWriter("../../..", writer); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); } // Problem 10: Rewrite the last exercises using XDocument, XElement and XAttribute. var xDocument = new XDocument(); xDocument.Add(CreateFileSystemXmlTree("../../../")); xDocument.Save("../../traverseWithXElement.xml"); // Problem 11: Write a program, which extract from the file catalog.xml the prices for all albums, published 5 years ago or earlier. // Use XPath query. doc.Load(PathToXmlFile); root = doc.DocumentElement; // returns all (no albums in the catalogue are newer...) var oldAlbumsPrices = root.SelectNodes("album/price[../year/text() < 2010]"); //// var oldAlbumsPrices = root.SelectNodes("album/price[../year/text() < 1980]"); // returns 2 albums' prices Console.WriteLine(new string('-', 50)); Console.WriteLine("Prices of the albums, published before 2010: "); foreach (var price in oldAlbumsPrices) { Console.WriteLine((price as XmlElement).InnerXml.Trim()); } // Problem 12: Rewrite the previous using LINQ query. Console.WriteLine(new string('-', 50)); Console.WriteLine("Prices of the albums, published before 2010 (using LINQ): "); var oldAlbumsPricesUsingLinq = from album in xDoc.Descendants("album") where int.Parse(album.Element("year").Value) < 2010 select album.Descendants("price").FirstOrDefault(); foreach (var price in oldAlbumsPricesUsingLinq) { Console.WriteLine(price.Value.Trim()); } // Problem 13: Create an XSL stylesheet, which transforms the file catalog.xml into HTML document, // formatted for viewing in a standard Web-browser. // Problem 14: Write a C# program to apply the XSLT stylesheet transformation on the file catalog.xml // using the class XslTransform. XslCompiledTransform catalogueXslt = new XslCompiledTransform(); catalogueXslt.Load("../../catalogue.xslt"); catalogueXslt.Transform(PathToXmlFile, "../../catalogue.html"); // Problem 15: // *Read some tutorial about the XQuery language. // Implement the XML to HTML transformation with XQuery (instead of XSLT). // Download some open source XQuery library for .NET and execute the XQuery to transform the catalog.xml to HTML. XQueryNavigatorCollection col = new XQueryNavigatorCollection(); // Add the XML document catalogue.xml to the collection using cat as the name to reference. col.AddNavigator("../../catalogue.xml", "cat"); var expr = new XQueryExpression( "<html><body><head><title>Catalogue</title></head>" + "<h1>Catalogue generated using XQuery</h1>" + "{For $a IN document(\"cat\")/catalogue/album " + "RETURN <div><strong>Title:</strong> {$a/name/text()}<br />" + "<strong>Artist:</strong> {$a/artist/text()}<br />" + "<strong>Year:</strong> {$a/year/text()}<br />" + "<strong>Producer:</strong> {$a/producer/text()}<br />" + "<strong>Price:</strong> {$a/price/text()}<br />" + "<strong>Songs:</strong><ol>{For $s IN $a/songs/song RETURN <li>{$s/title/text()}</li>}</ol>" + "</div><hr />}</body></html>"); StreamWriter str = new StreamWriter("../../catalogueUsingXQuery.html"); XQueryNavigator nav = expr.Execute(col); nav.ToXml(str); str.Close(); // Problem 16: // Using Visual Studio generate an XSD schema for the file catalog.xml. // Write a C# program that takes an XML file and an XSD file (schema) and validates the XML file against the schema. // Test it with valid XML catalogs and invalid XML catalogs. string xsdMarkup = File.ReadAllText("../../catalogue.xsd"); XmlSchemaSet schemas = new XmlSchemaSet(); schemas.Add(string.Empty, XmlReader.Create(new StringReader(xsdMarkup))); XDocument valid = XDocument.Load(PathToXmlFile); XDocument invalid = new XDocument( new XElement( "Root", new XElement("Child1", "content1"), new XElement("Child2", "content2"))); Console.WriteLine(new string('-', 50)); Console.WriteLine("Validating valid document:"); bool errors = false; valid.Validate(schemas, (o, e) => { Console.WriteLine("{0}", e.Message); errors = true; }); Console.WriteLine("Valid {0}", errors ? "did not validate" : "validated"); Console.WriteLine(); Console.WriteLine("Validating invalid document:"); errors = false; invalid.Validate(schemas, (o, e) => { Console.WriteLine("{0}", e.Message); errors = true; }); Console.WriteLine("doc2 {0}", errors ? "did not validate" : "validated"); }