Exemple #1
0
        private void GraphToTriX(IGraph g, XmlWriter writer)
        {
            // Create the <graph> element
            writer.WriteStartElement("graph");

            // Is the Graph Named?
            if (g.BaseUri != null)
            {
                if (!g.BaseUri.AbsoluteUri.StartsWith("trix:local:"))
                {
                    writer.WriteStartElement("uri");
                    writer.WriteRaw(WriterHelper.EncodeForXml(g.BaseUri.AbsoluteUri));
                    writer.WriteEndElement();
                }
                else
                {
                    writer.WriteStartElement("id");
                    writer.WriteRaw(WriterHelper.EncodeForXml(g.BaseUri.AbsoluteUri.Substring(11)));
                    writer.WriteEndElement();
                }
            }

            // Output the Triples
            foreach (Triple t in g.Triples)
            {
                writer.WriteStartElement("triple");

                this.NodeToTriX(t.Subject, writer);
                this.NodeToTriX(t.Predicate, writer);
                this.NodeToTriX(t.Object, writer);

                // </triple>
                writer.WriteEndElement();
            }

            // </graph>
            writer.WriteEndElement();
        }
Exemple #2
0
        /// <summary>
        /// Method which generates the Sparql Query Results XML Format serialization of the Result Set
        /// </summary>
        /// <returns></returns>
        protected void GenerateOutput(SparqlResultSet resultSet, XmlWriter writer)
        {
            // XML Declaration
            writer.WriteStartDocument();

            // <sparql> element
            writer.WriteStartElement("sparql", SparqlSpecsHelper.SparqlNamespace);

            // <head> element
            writer.WriteStartElement("head");

            // Variables in the Header?
            if (resultSet.ResultsType == SparqlResultsType.VariableBindings)
            {
                foreach (String var in resultSet.Variables)
                {
                    // <variable> element
                    writer.WriteStartElement("variable");
                    writer.WriteAttributeString("name", var);
                    writer.WriteEndElement();
                }

                // </head> Element
                writer.WriteEndElement();

                // <results> Element
                writer.WriteStartElement("results");

                foreach (SparqlResult r in resultSet.Results)
                {
                    // <result> Element
                    writer.WriteStartElement("result");

                    foreach (String var in resultSet.Variables)
                    {
                        if (r.HasValue(var))
                        {
                            INode n = r.Value(var);
                            if (n == null)
                            {
                                continue;            //NULLs don't get serialized in the XML Format
                            }
                            // <binding> Element
                            writer.WriteStartElement("binding");
                            writer.WriteAttributeString("name", var);

                            switch (n.NodeType)
                            {
                            case NodeType.Blank:
                                // <bnode> element
                                writer.WriteStartElement("bnode");
                                writer.WriteRaw(((IBlankNode)n).InternalID);
                                writer.WriteEndElement();
                                break;

                            case NodeType.GraphLiteral:
                                // Error!
                                throw new RdfOutputException("Result Sets which contain Graph Literal Nodes cannot be serialized in the SPARQL Query Results XML Format");

                            case NodeType.Literal:
                                // <literal> element
                                writer.WriteStartElement("literal");
                                ILiteralNode l = (ILiteralNode)n;

                                if (!l.Language.Equals(String.Empty))
                                {
                                    writer.WriteStartAttribute("xml", "lang", XmlSpecsHelper.NamespaceXml);
                                    writer.WriteRaw(l.Language);
                                    writer.WriteEndAttribute();
                                }
                                else if (l.DataType != null)
                                {
                                    writer.WriteStartAttribute("datatype");
                                    writer.WriteRaw(WriterHelper.EncodeForXml(l.DataType.AbsoluteUri));
                                    writer.WriteEndAttribute();
                                }

                                // Write the Value and the </literal>
                                writer.WriteRaw(WriterHelper.EncodeForXml(l.Value));
                                writer.WriteEndElement();
                                break;

                            case NodeType.Uri:
                                // <uri> element
                                writer.WriteStartElement("uri");
                                writer.WriteRaw(WriterHelper.EncodeForXml(((IUriNode)n).Uri.AbsoluteUri));
                                writer.WriteEndElement();
                                break;

                            default:
                                throw new RdfOutputException("Result Sets which contain Nodes of unknown Type cannot be serialized in the SPARQL Query Results XML Format");
                            }

                            // </binding> element
                            writer.WriteEndElement();
                        }
                    }

                    // </result> element
                    writer.WriteEndElement();
                }

                // </results>
                writer.WriteEndElement();
            }
            else
            {
                // </head>
                writer.WriteEndElement();

                // <boolean> element
                writer.WriteStartElement("boolean");
                writer.WriteRaw(resultSet.Result.ToString().ToLower());
                writer.WriteEndElement();
            }

            // </sparql> element
            writer.WriteEndElement();

            // End Document
            writer.WriteEndDocument();
            writer.Flush();
            writer.Close();
        }
        /// <summary>
        /// Internal method which generates the RDF/Json Output for a Graph
        /// </summary>
        /// <param name="g">Graph to save</param>
        /// <param name="output">Stream to save to</param>
        private void GenerateOutput(IGraph g, TextWriter output)
        {
            // Always force RDF Namespace to be correctly defined
            g.NamespaceMap.Import(this._defaultNamespaces);
            g.NamespaceMap.AddNamespace("rdf", UriFactory.Create(NamespaceMapper.RDF));

            // Create our Writer Context and start the XML Document
            RdfXmlWriterContext context = new RdfXmlWriterContext(g, output);

            context.CompressionLevel = this._compressionLevel;
            context.UseDtd           = this._useDTD;
            context.Writer.WriteStartDocument();

            if (context.UseDtd)
            {
                // Create the DOCTYPE declaration
                StringBuilder entities = new StringBuilder();
                String        uri;
                entities.Append('\n');
                foreach (String prefix in context.NamespaceMap.Prefixes)
                {
                    uri = context.NamespaceMap.GetNamespaceUri(prefix).AbsoluteUri;
                    if (!uri.Equals(context.NamespaceMap.GetNamespaceUri(prefix).ToString()))
                    {
                        context.UseDtd = false;
                        break;
                    }
                    if (!prefix.Equals(String.Empty))
                    {
                        entities.AppendLine("\t<!ENTITY " + prefix + " '" + uri + "'>");
                    }
                }
                if (context.UseDtd)
                {
                    context.Writer.WriteDocType("rdf:RDF", null, null, entities.ToString());
                }
            }

            // Create the rdf:RDF element
            context.Writer.WriteStartElement("rdf", "RDF", NamespaceMapper.RDF);
            if (context.Graph.BaseUri != null)
            {
                context.Writer.WriteAttributeString("xml", "base", null, context.Graph.BaseUri.AbsoluteUri);//Uri.EscapeUriString(context.Graph.BaseUri.ToString()));
            }
            context.NamespaceMap.IncrementNesting();
            foreach (String prefix in context.NamespaceMap.Prefixes)
            {
                if (prefix.Equals("rdf"))
                {
                    continue;
                }

                if (!prefix.Equals(String.Empty))
                {
                    context.Writer.WriteStartAttribute("xmlns", prefix, null);
                    // String nsRef = "&" + prefix + ";";
                    // context.Writer.WriteRaw(nsRef);
                    // context.Writer.WriteEntityRef(prefix);
                    context.Writer.WriteRaw(WriterHelper.EncodeForXml(context.NamespaceMap.GetNamespaceUri(prefix).AbsoluteUri));//Uri.EscapeUriString(WriterHelper.EncodeForXml(context.NamespaceMap.GetNamespaceUri(prefix).AbsoluteUri)));
                    context.Writer.WriteEndAttribute();
                }
                else
                {
                    context.Writer.WriteStartAttribute("xmlns");
                    context.Writer.WriteRaw(WriterHelper.EncodeForXml(context.NamespaceMap.GetNamespaceUri(prefix).AbsoluteUri));//Uri.EscapeUriString(WriterHelper.EncodeForXml(context.NamespaceMap.GetNamespaceUri(prefix).AbsoluteUri)));
                    context.Writer.WriteEndAttribute();
                }
            }

            // Find the Collections and Type References
            if (context.CompressionLevel >= WriterCompressionLevel.More)
            {
                WriterHelper.FindCollections(context, CollectionSearchMode.ImplicitOnly);
                // WriterHelper.FindCollections(context, CollectionSearchMode.All);
            }
            Dictionary <INode, String> typerefs = this.FindTypeReferences(context);

            // Get the Triples as a Sorted List
            List <Triple> ts = context.Graph.Triples.Where(t => !context.TriplesDone.Contains(t)).ToList();

            ts.Sort(new RdfXmlTripleComparer());

            // Variables we need to track our writing
            INode lastSubj, lastPred, lastObj;

            lastSubj = lastPred = lastObj = null;

            for (int i = 0; i < ts.Count; i++)
            {
                Triple t = ts[i];
                if (context.TriplesDone.Contains(t))
                {
                    continue;                                  //Skip if already done
                }
                if (lastSubj == null || !t.Subject.Equals(lastSubj))
                {
                    // Start a new set of Triples
                    if (lastSubj != null)
                    {
                        context.NamespaceMap.DecrementNesting();
                        context.Writer.WriteEndElement();
                    }
                    if (lastPred != null)
                    {
                        context.NamespaceMap.DecrementNesting();
                        context.Writer.WriteEndElement();
                    }

                    // Write out the Subject
                    // Validate Subject
                    // Use a Type Reference if applicable
                    context.NamespaceMap.IncrementNesting();
                    if (typerefs.ContainsKey(t.Subject))
                    {
                        String tref = typerefs[t.Subject];
                        if (tref.StartsWith(":"))
                        {
                            context.Writer.WriteStartElement(tref.Substring(1));
                        }
                        else if (tref.Contains(":"))
                        {
                            context.Writer.WriteStartElement(tref.Substring(0, tref.IndexOf(':')), tref.Substring(tref.IndexOf(':') + 1), null);
                        }
                        else
                        {
                            context.Writer.WriteStartElement(tref);
                        }
                    }
                    else
                    {
                        context.Writer.WriteStartElement("rdf", "Description", NamespaceMapper.RDF);
                    }
                    lastSubj = t.Subject;

                    // Apply appropriate attributes
                    switch (t.Subject.NodeType)
                    {
                    case NodeType.GraphLiteral:
                        throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("RDF/XML"));

                    case NodeType.Literal:
                        throw new RdfOutputException(WriterErrorMessages.LiteralSubjectsUnserializable("RDF/XML"));

                    case NodeType.Blank:
                        if (context.Collections.ContainsKey(t.Subject))
                        {
                            this.GenerateCollectionOutput(context, t.Subject);
                        }
                        else
                        {
                            context.Writer.WriteAttributeString("rdf", "nodeID", null, context.BlankNodeMapper.GetOutputID(((IBlankNode)t.Subject).InternalID));
                        }
                        break;

                    case NodeType.Uri:
                        this.GenerateUriOutput(context, (IUriNode)t.Subject, "rdf:about");
                        break;

                    default:
                        throw new RdfOutputException(WriterErrorMessages.UnknownNodeTypeUnserializable("RDF/XML"));
                    }

                    // Write the Predicate
                    context.NamespaceMap.IncrementNesting();
                    this.GeneratePredicateNode(context, t.Predicate);
                    lastPred = t.Predicate;
                    lastObj  = null;
                }
                else if (lastPred == null || !t.Predicate.Equals(lastPred))
                {
                    if (lastPred != null)
                    {
                        context.NamespaceMap.DecrementNesting();
                        context.Writer.WriteEndElement();
                    }

                    // Write the Predicate
                    context.NamespaceMap.IncrementNesting();
                    this.GeneratePredicateNode(context, t.Predicate);
                    lastPred = t.Predicate;
                    lastObj  = null;
                }

                // Write the Object
                if (lastObj != null)
                {
                    // Terminate the previous Predicate Node
                    context.NamespaceMap.DecrementNesting();
                    context.Writer.WriteEndElement();

                    // Start a new Predicate Node
                    context.NamespaceMap.DecrementNesting();
                    context.Writer.WriteEndElement();
                    context.NamespaceMap.IncrementNesting();
                    this.GeneratePredicateNode(context, t.Predicate);
                }
                // Create an Object for the Object
                switch (t.Object.NodeType)
                {
                case NodeType.Blank:
                    if (context.Collections.ContainsKey(t.Object))
                    {
                        // Output a Collection
                        this.GenerateCollectionOutput(context, t.Object);
                    }
                    else
                    {
                        // Terminate the Blank Node triple by adding a rdf:nodeID attribute
                        context.Writer.WriteAttributeString("rdf", "nodeID", null, context.BlankNodeMapper.GetOutputID(((IBlankNode)t.Object).InternalID));
                    }

                    break;

                case NodeType.GraphLiteral:
                    throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("RDF/XML"));

                case NodeType.Literal:
                    ILiteralNode lit = (ILiteralNode)t.Object;
                    this.GenerateLiteralOutput(context, lit);

                    break;

                case NodeType.Uri:
                    this.GenerateUriOutput(context, (IUriNode)t.Object, "rdf:resource");
                    break;

                default:
                    throw new RdfOutputException(WriterErrorMessages.UnknownNodeTypeUnserializable("RDF/XML"));
                }
                lastObj = t.Object;

                // Force a new Predicate Node
                context.NamespaceMap.DecrementNesting();
                context.Writer.WriteEndElement();
                lastPred = null;

                context.TriplesDone.Add(t);
            }

            // Check we haven't failed to output any collections
            foreach (KeyValuePair <INode, OutputRdfCollection> pair in context.Collections)
            {
                if (pair.Value.Triples.Count > 0)
                {
                    if (typerefs.ContainsKey(pair.Key))
                    {
                        String tref = typerefs[pair.Key];
                        context.NamespaceMap.IncrementNesting();
                        if (tref.StartsWith(":"))
                        {
                            context.Writer.WriteStartElement(tref.Substring(1));
                        }
                        else if (tref.Contains(":"))
                        {
                            context.Writer.WriteStartElement(tref.Substring(0, tref.IndexOf(':')), tref.Substring(tref.IndexOf(':') + 1), null);
                        }
                        else
                        {
                            context.Writer.WriteStartElement(tref);
                        }

                        this.GenerateCollectionOutput(context, pair.Key);

                        context.Writer.WriteEndElement();
                    }
                    else
                    {
                        context.Writer.WriteStartElement("rdf", "Description", NamespaceMapper.RDF);
                        context.Writer.WriteAttributeString("rdf", "nodeID", NamespaceMapper.RDF, context.BlankNodeMapper.GetOutputID(((IBlankNode)pair.Key).InternalID));
                        this.GenerateCollectionOutput(context, pair.Key);
                        context.Writer.WriteEndElement();
                        // throw new RdfOutputException("Failed to output a Collection due to an unknown error");
                    }
                }
            }

            context.NamespaceMap.DecrementNesting();
            context.Writer.WriteEndDocument();

            // Save to the Output Stream
            context.Writer.Flush();
        }
        public void WritingXmlAmpersandEscaping()
        {
            List <String> inputs = new List <string>()
            {
                "&value",
                "&amp;",
                "&",
                "&value&next",
                "& &squot; < > ' \"",
                new String('&', 1000)
            };

            List <String> outputs = new List <string>()
            {
                "&amp;value",
                "&amp;",
                "&amp;",
                "&amp;value&amp;next",
                "&amp; &squot; &lt; &gt; &apos; &quot;"
            };
            StringBuilder temp = new StringBuilder();

            for (int i = 0; i < 1000; i++)
            {
                temp.Append("&amp;");
            }
            outputs.Add(temp.ToString());

            for (int i = 0; i < inputs.Count; i++)
            {
                Console.WriteLine("Input: " + inputs[i] + " - Expected Output: " + outputs[i] + " - Actual Output: " + WriterHelper.EncodeForXml(inputs[i]));
                Assert.AreEqual(outputs[i], WriterHelper.EncodeForXml(inputs[i]), "Ampersands should have been encoded correctly");
            }
        }
        /// <summary>
        /// Method which generates the Sparql Query Results XML Format serialization of the Result Set
        /// </summary>
        /// <returns></returns>
        protected XmlDocument GenerateOutput(SparqlResultSet resultSet)
        {
            XmlDocument xmlDoc = new XmlDocument();

            //XML Declaration
            XmlDeclaration xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", String.Empty);

            xmlDoc.AppendChild(xmlDec);

            //<sparql> element
            XmlElement   sparql   = xmlDoc.CreateElement("sparql");
            XmlAttribute sparqlns = xmlDoc.CreateAttribute("xmlns");

            sparqlns.Value = SparqlSpecsHelper.SparqlNamespace;
            sparql.Attributes.Append(sparqlns);
            xmlDoc.AppendChild(sparql);

            //<head> element
            XmlElement head = xmlDoc.CreateElement("head");

            sparql.AppendChild(head);

            //Variables in the Header?
            if (resultSet.ResultsType == SparqlResultsType.VariableBindings)
            {
                foreach (String var in resultSet.Variables)
                {
                    //<variable> element
                    XmlElement   varEl   = xmlDoc.CreateElement("variable");
                    XmlAttribute varAttr = xmlDoc.CreateAttribute("name");
                    varAttr.Value = var;
                    varEl.Attributes.Append(varAttr);
                    head.AppendChild(varEl);
                }

                //<results> Element
                XmlElement results = xmlDoc.CreateElement("results");
                sparql.AppendChild(results);

                foreach (SparqlResult r in resultSet.Results)
                {
                    //<result> Element
                    XmlElement result = xmlDoc.CreateElement("result");
                    results.AppendChild(result);

                    foreach (String var in resultSet.Variables)
                    {
                        if (r.HasValue(var))
                        {
                            //<binding> Element
                            XmlElement   binding = xmlDoc.CreateElement("binding");
                            XmlAttribute name    = xmlDoc.CreateAttribute("name");
                            name.Value = var;
                            binding.Attributes.Append(name);

                            INode n = r.Value(var);
                            if (n == null)
                            {
                                continue;            //NULLs don't get serialized in the XML Format
                            }
                            switch (n.NodeType)
                            {
                            case NodeType.Blank:
                                //<bnode> element
                                XmlElement bnode = xmlDoc.CreateElement("bnode");
                                bnode.InnerText = ((IBlankNode)n).InternalID;
                                binding.AppendChild(bnode);
                                break;

                            case NodeType.GraphLiteral:
                                //Error!
                                throw new RdfOutputException("Result Sets which contain Graph Literal Nodes cannot be serialized in the SPARQL Query Results XML Format");

                            case NodeType.Literal:
                                //<literal> element
                                XmlElement   lit = xmlDoc.CreateElement("literal");
                                ILiteralNode l   = (ILiteralNode)n;
                                lit.InnerText = l.Value;

                                if (!l.Language.Equals(String.Empty))
                                {
                                    XmlAttribute lang = xmlDoc.CreateAttribute("xml:lang");
                                    lang.Value = l.Language;
                                    lit.Attributes.Append(lang);
                                }
                                else if (l.DataType != null)
                                {
                                    XmlAttribute dt = xmlDoc.CreateAttribute("datatype");
                                    dt.Value = WriterHelper.EncodeForXml(l.DataType.ToString());
                                    lit.Attributes.Append(dt);
                                }

                                binding.AppendChild(lit);
                                break;

                            case NodeType.Uri:
                                //<uri> element
                                XmlElement uri = xmlDoc.CreateElement("uri");
                                uri.InnerText = WriterHelper.EncodeForXml(((IUriNode)n).StringUri);
                                binding.AppendChild(uri);
                                break;

                            default:
                                throw new RdfOutputException("Result Sets which contain Nodes of unknown Type cannot be serialized in the SPARQL Query Results XML Format");
                            }

                            result.AppendChild(binding);
                        }
                    }
                }
            }
            else
            {
                XmlElement boolRes = xmlDoc.CreateElement("boolean");
                boolRes.InnerText = resultSet.Result.ToString().ToLower();
                sparql.AppendChild(boolRes);
            }

            return(xmlDoc);
        }