/// <summary> /// Parses the current quadruple of the data reader /// </summary> public static RDFQuadruple ParseQuadruple(IDataReader fetchedQuadruples) { if (fetchedQuadruples != null) { RDFContext qContext = new RDFContext(fetchedQuadruples["Context"].ToString()); RDFResource qSubject = new RDFResource(fetchedQuadruples["Subject"].ToString()); RDFResource qPredicate = new RDFResource(fetchedQuadruples["Predicate"].ToString()); //SPO-flavour quadruple if (fetchedQuadruples["TripleFlavor"].ToString() == "1") { RDFResource qObject = new RDFResource(fetchedQuadruples["Object"].ToString()); return new RDFQuadruple(qContext, qSubject, qPredicate, qObject); } //SPL-flavour quadruple String literal = fetchedQuadruples["Object"].ToString(); //PlainLiteral if (!literal.Contains("^^") || literal.EndsWith("^^") || RDFModelUtilities.GetUriFromString(literal.Substring(literal.LastIndexOf("^^", StringComparison.Ordinal) + 2)) == null) { RDFPlainLiteral pLit = null; if (literal.Contains("@")) { if (!literal.EndsWith("@")) { Int32 lastAmp = literal.LastIndexOf('@'); pLit = new RDFPlainLiteral(literal.Substring(0, lastAmp), literal.Substring(lastAmp + 1)); } else { pLit = new RDFPlainLiteral(literal); } } else { pLit = new RDFPlainLiteral(literal); } return new RDFQuadruple(qContext, qSubject, qPredicate, pLit); } //TypedLiteral String tLitValue = literal.Substring(0, literal.LastIndexOf("^^", StringComparison.Ordinal)); String tLitDatatype = literal.Substring(literal.LastIndexOf("^^", StringComparison.Ordinal) + 2); RDFDatatype dt = RDFModelUtilities.GetDatatypeFromString(tLitDatatype); RDFTypedLiteral tLit = new RDFTypedLiteral(tLitValue, dt); return new RDFQuadruple(qContext, qSubject, qPredicate, tLit); } throw new RDFStoreException("Cannot parse quadruple because given \"fetchedQuadruples\" parameter is null."); }
/// <summary> /// Parses the given string to return an instance of pattern member /// </summary> public static RDFPatternMember ParseRDFPatternMember(String pMember) { if (pMember != null) { #region Uri Uri testUri; if (Uri.TryCreate(pMember, UriKind.Absolute, out testUri)) { return new RDFResource(pMember); } #endregion #region Plain Literal if (!pMember.Contains("^^") || pMember.EndsWith("^^") || RDFModelUtilities.GetUriFromString(pMember.Substring(pMember.LastIndexOf("^^", StringComparison.Ordinal) + 2)) == null) { RDFPlainLiteral pLit = null; if (pMember.Contains("@")) { if (!pMember.EndsWith("@")) { Int32 lastAmp = pMember.LastIndexOf('@'); pLit = new RDFPlainLiteral(pMember.Substring(0, lastAmp), pMember.Substring(lastAmp + 1)); } else { pLit = new RDFPlainLiteral(pMember); } } else { pLit = new RDFPlainLiteral(pMember); } return pLit; } #endregion #region Typed Literal String tLitValue = pMember.Substring(0, pMember.LastIndexOf("^^", StringComparison.Ordinal)); String tLitDatatype = pMember.Substring(pMember.LastIndexOf("^^", StringComparison.Ordinal) + 2); RDFDatatype dt = RDFModelUtilities.GetDatatypeFromString(tLitDatatype); RDFTypedLiteral tLit = new RDFTypedLiteral(tLitValue, dt); return tLit; #endregion } throw new RDFQueryException("Cannot parse pattern member because given \"pMember\" parameter is null."); }
/// <summary> /// Parses the given string to return an instance of pattern member /// </summary> internal static RDFPatternMember ParseRDFPatternMember(String pMember) { if (pMember != null) { #region Uri Uri testUri; if (Uri.TryCreate(pMember, UriKind.Absolute, out testUri)) { return new RDFResource(pMember); } #endregion #region Plain Literal if (!pMember.Contains("^^") || pMember.EndsWith("^^") || RDFModelUtilities.GetUriFromString(pMember.Substring(pMember.LastIndexOf("^^", StringComparison.Ordinal) + 2)) == null) { RDFPlainLiteral pLit = null; if (RDFNTriples.regexLPL.Match(pMember).Success) { String pLitVal = pMember.Substring(0, pMember.LastIndexOf("@", StringComparison.Ordinal)); String pLitLng = pMember.Substring(pMember.LastIndexOf("@", StringComparison.Ordinal) + 1); pLit = new RDFPlainLiteral(pLitVal, pLitLng); } else { pLit = new RDFPlainLiteral(pMember); } return pLit; } #endregion #region Typed Literal String tLitValue = pMember.Substring(0, pMember.LastIndexOf("^^", StringComparison.Ordinal)); String tLitDatatype = pMember.Substring(pMember.LastIndexOf("^^", StringComparison.Ordinal) + 2); RDFModelEnums.RDFDatatypes dt = RDFModelUtilities.GetDatatypeFromString(tLitDatatype); RDFTypedLiteral tLit = new RDFTypedLiteral(tLitValue, dt); return tLit; #endregion } throw new RDFQueryException("Cannot parse pattern member because given \"pMember\" parameter is null."); }
/// <summary> /// Given an element representing a RDF container, iterates on its constituent elements /// to build its standard reification triples. /// </summary> internal static void ParseContainerElements(RDFModelEnums.RDFContainerTypes contType, XmlNode container, RDFResource subj, RDFResource pred, RDFGraph result) { //Attach the container as the blank object of the current pred RDFResource obj = new RDFResource(); result.AddTriple(new RDFTriple(subj, pred, obj)); //obj -> rdf:type -> rdf:[Bag|Seq|Alt] switch (contType) { case RDFModelEnums.RDFContainerTypes.Bag: result.AddTriple(new RDFTriple(obj, RDFVocabulary.RDF.TYPE, RDFVocabulary.RDF.BAG)); break; case RDFModelEnums.RDFContainerTypes.Seq: result.AddTriple(new RDFTriple(obj, RDFVocabulary.RDF.TYPE, RDFVocabulary.RDF.SEQ)); break; default: result.AddTriple(new RDFTriple(obj, RDFVocabulary.RDF.TYPE, RDFVocabulary.RDF.ALT)); break; } //Iterate on the container items if (container.HasChildNodes) { IEnumerator elems = container.ChildNodes.GetEnumerator(); List<String> elemVals = new List<String>(); while (elems != null && elems.MoveNext()) { XmlNode elem = (XmlNode)elems.Current; XmlAttribute elemUri = GetRdfResourceAttribute(elem); #region Container Resource Item //This is a container of resources if (elemUri != null) { //Sanitize eventual blank node value detected by presence of "nodeID" attribute if (elemUri.LocalName.Equals("nodeID", StringComparison.Ordinal)) { if (!elemUri.Value.StartsWith("bnode:")) { elemUri.Value = "bnode:" + elemUri.Value; } } //obj -> rdf:_N -> VALUE if (contType == RDFModelEnums.RDFContainerTypes.Alt) { if (!elemVals.Contains(elemUri.Value)) { elemVals.Add(elemUri.Value); result.AddTriple(new RDFTriple(obj, new RDFResource(RDFVocabulary.RDF.BASE_URI + elem.LocalName), new RDFResource(elemUri.Value))); } } else { result.AddTriple(new RDFTriple(obj, new RDFResource(RDFVocabulary.RDF.BASE_URI + elem.LocalName), new RDFResource(elemUri.Value))); } } #endregion #region Container Literal Item //This is a container of literals else { //Parse the literal contained in the item RDFLiteral literal = null; XmlAttribute attr = GetRdfDatatypeAttribute(elem); if (attr != null) { literal = new RDFTypedLiteral(elem.InnerText, RDFModelUtilities.GetDatatypeFromString(attr.InnerText)); } else { attr = GetXmlLangAttribute(elem); literal = new RDFPlainLiteral(elem.InnerText, (attr != null ? attr.InnerText : String.Empty)); } //obj -> rdf:_N -> VALUE if (contType == RDFModelEnums.RDFContainerTypes.Alt) { if (!elemVals.Contains(literal.ToString())) { elemVals.Add(literal.ToString()); result.AddTriple(new RDFTriple(obj, new RDFResource(RDFVocabulary.RDF.BASE_URI + elem.LocalName), literal)); } } else { result.AddTriple(new RDFTriple(obj, new RDFResource(RDFVocabulary.RDF.BASE_URI + elem.LocalName), literal)); } } #endregion } } }
/// <summary> /// Deserializes the given N-Triples stream to a graph. /// </summary> internal static RDFGraph Deserialize(Stream inputStream) { Int64 ntripleIndex = 0; try { #region deserialize using (StreamReader sr = new StreamReader(inputStream, Encoding.ASCII)) { RDFGraph result = new RDFGraph(); String ntriple = String.Empty; String[] tokens = new String[3]; RDFResource S = null; RDFResource P = null; RDFResource O = null; RDFLiteral L = null; while ((ntriple = sr.ReadLine()) != null) { ntripleIndex++; #region sanitize & tokenize //Cleanup previous data S = null; tokens[0] = String.Empty; P = null; tokens[1] = String.Empty; O = null; L = null; tokens[2] = String.Empty; //Preliminary sanitizations: clean trailing space-like chars ntriple = ntriple.Trim(new Char[] { ' ', '\t', '\r', '\n' }); //Skip empty or comment lines if (ntriple == String.Empty || ntriple.StartsWith("#")) { continue; } //Tokenizes the sanitized triple tokens = TokenizeNTriple(ntriple); #endregion #region subj String subj = tokens[0].TrimStart(new Char[] { '<' }) .TrimEnd(new Char[] { '>' }) .Replace("_:", "bnode:"); S = new RDFResource(RDFModelUtilities.ASCII_To_Unicode(subj)); #endregion #region pred String pred = tokens[1].TrimStart(new Char[] { '<' }) .TrimEnd(new Char[] { '>' }); P = new RDFResource(RDFModelUtilities.ASCII_To_Unicode(pred)); #endregion #region object if (tokens[2].StartsWith("<") || tokens[2].StartsWith("bnode:") || tokens[2].StartsWith("_:")) { String obj = tokens[2].TrimStart(new Char[] { '<' }) .TrimEnd(new Char[] { '>' }) .Replace("_:", "bnode:") .Trim(new Char[] { ' ', '\n', '\t', '\r' }); O = new RDFResource(RDFModelUtilities.ASCII_To_Unicode(obj)); } #endregion #region literal else { #region sanitize tokens[2] = regexSqt.Replace(tokens[2], String.Empty); tokens[2] = regexEqt.Replace(tokens[2], String.Empty); tokens[2] = tokens[2].Replace("\\\\", "\\") .Replace("\\\"", "\"") .Replace("\\n", "\n") .Replace("\\t", "\t") .Replace("\\r", "\r"); tokens[2] = RDFModelUtilities.ASCII_To_Unicode(tokens[2]); #endregion #region plain literal if (!tokens[2].Contains("^^") || tokens[2].EndsWith("^^") || tokens[2].Substring(tokens[2].LastIndexOf("^^", StringComparison.Ordinal) + 2, 1) != "<") { if (regexLPL.Match(tokens[2]).Success) { tokens[2] = tokens[2].Replace("\"@", "@"); String pLitValue = tokens[2].Substring(0, tokens[2].LastIndexOf("@", StringComparison.Ordinal)); String pLitLang = tokens[2].Substring(tokens[2].LastIndexOf("@", StringComparison.Ordinal) + 1); L = new RDFPlainLiteral(HttpUtility.HtmlDecode(pLitValue), pLitLang); } else { L = new RDFPlainLiteral(HttpUtility.HtmlDecode(tokens[2])); } } #endregion #region typed literal else { tokens[2] = tokens[2].Replace("\"^^", "^^"); String tLitValue = tokens[2].Substring(0, tokens[2].LastIndexOf("^^", StringComparison.Ordinal)); String tLitDatatype = tokens[2].Substring(tokens[2].LastIndexOf("^^", StringComparison.Ordinal) + 2) .TrimStart(new Char[] { '<' }) .TrimEnd(new Char[] { '>' }); RDFModelEnums.RDFDatatypes dt = RDFModelUtilities.GetDatatypeFromString(tLitDatatype); L = new RDFTypedLiteral(HttpUtility.HtmlDecode(tLitValue), dt); } #endregion } #endregion #region addtriple if (O != null) { result.AddTriple(new RDFTriple(S, P, O)); } else { result.AddTriple(new RDFTriple(S, P, L)); } #endregion } return(result); } #endregion } catch (Exception ex) { throw new RDFModelException("Cannot deserialize N-Triples (line " + ntripleIndex + ") because: " + ex.Message, ex); } }
/// <summary> /// Given an element representing a RDF container, iterates on its constituent elements /// to build its standard reification triples. /// </summary> internal static void ParseContainerElements(RDFModelEnums.RDFContainerType contType, XmlNode container, RDFResource subj, RDFResource pred, RDFGraph result) { //Attach the container as the blank object of the current pred RDFResource obj = new RDFResource(); result.AddTriple(new RDFTriple(subj, pred, obj)); //obj -> rdf:type -> rdf:[Bag|Seq|Alt] switch (contType) { case RDFModelEnums.RDFContainerType.Bag: result.AddTriple(new RDFTriple(obj, RDFVocabulary.RDF.TYPE, RDFVocabulary.RDF.BAG)); break; case RDFModelEnums.RDFContainerType.Seq: result.AddTriple(new RDFTriple(obj, RDFVocabulary.RDF.TYPE, RDFVocabulary.RDF.SEQ)); break; default: result.AddTriple(new RDFTriple(obj, RDFVocabulary.RDF.TYPE, RDFVocabulary.RDF.ALT)); break; } //Iterate on the container items if (container.HasChildNodes) { IEnumerator elems = container.ChildNodes.GetEnumerator(); List <String> elemVals = new List <String>(); while (elems != null && elems.MoveNext()) { XmlNode elem = (XmlNode)elems.Current; XmlAttribute elemUri = GetRdfResourceAttribute(elem); #region Container Resource Item //This is a container of resources if (elemUri != null) { //Sanitize eventual blank node value detected by presence of "nodeID" attribute if (elemUri.LocalName.Equals("nodeID", StringComparison.Ordinal)) { if (!elemUri.Value.StartsWith("bnode:")) { elemUri.Value = "bnode:" + elemUri.Value; } } //obj -> rdf:_N -> VALUE if (contType == RDFModelEnums.RDFContainerType.Alt) { if (!elemVals.Contains(elemUri.Value)) { elemVals.Add(elemUri.Value); result.AddTriple(new RDFTriple(obj, new RDFResource(RDFVocabulary.RDF.BASE_URI + elem.LocalName), new RDFResource(elemUri.Value))); } } else { result.AddTriple(new RDFTriple(obj, new RDFResource(RDFVocabulary.RDF.BASE_URI + elem.LocalName), new RDFResource(elemUri.Value))); } } #endregion #region Container Literal Item //This is a container of literals else { //Parse the literal contained in the item RDFLiteral literal = null; XmlAttribute attr = GetRdfDatatypeAttribute(elem); if (attr != null) { literal = new RDFTypedLiteral(elem.InnerText, RDFModelUtilities.GetDatatypeFromString(attr.InnerText)); } else { attr = GetXmlLangAttribute(elem); literal = new RDFPlainLiteral(elem.InnerText, (attr != null ? attr.InnerText : String.Empty)); } //obj -> rdf:_N -> VALUE if (contType == RDFModelEnums.RDFContainerType.Alt) { if (!elemVals.Contains(literal.ToString())) { elemVals.Add(literal.ToString()); result.AddTriple(new RDFTriple(obj, new RDFResource(RDFVocabulary.RDF.BASE_URI + elem.LocalName), literal)); } } else { result.AddTriple(new RDFTriple(obj, new RDFResource(RDFVocabulary.RDF.BASE_URI + elem.LocalName), literal)); } } #endregion } } }
protected void LoadRDF() { // First we set some core RDF resources // agent refers to artist(s) RDFResource type = RDFVocabulary.RDF.TYPE; RDFResource name = RDFVocabulary.FOAF.NAME; RDFResource agent = RDFVocabulary.FOAF.AGENT; // TGN is a Getty vocabulary for locations // TGN added to RDFSharp vocabularies manually. TGN ID is stored in TMSThes (or equivalent in TMS 2014+) RDFResource tgn = new RDFResource(RDFVocabulary.TGN.BASE_URI); // The predicates below are often part of ULAN (which we don't have) // unsure if using bio events this way is acceptable... RDFResource livedIn = new RDFResource("http://purl.org/vocab/bio/0.1/event/livedIn"); RDFResource activeIn = new RDFResource("http://purl.org/vocab/bio/0.1/event/activeIn"); RDFResource educatedIn = new RDFResource("http://purl.org/vocab/bio/0.1/event/educatedIn"); RDFResource bornIn = new RDFResource("http://purl.org/vocab/bio/0.1/event/bornIn"); RDFResource diedIn = new RDFResource("http://purl.org/vocab/bio/0.1/event/diedIn"); RDFResource anUri = new RDFResource("http://example.org/uris#anUri"); // The following entries are all generated from SQL queries which you can find in the file SQL.txt Technically we could load them into the database directly, // but this allows us to see how a resource is "built" and it creates the correct RDF format files (NTriples, RdfXml, TriX), as well as inserts into the db. // Once in the db, we do not need to run LoadRDF() except to refresh data. #region Artists (agents) // Ideally this would reference the Getty vocabulary for ULAN but we don't have the ULAN ID stored in the db RDFResource raimundabraham = new RDFResource("http://example.org/artists/47"); RDFResource emilioambasz = new RDFResource("http://example.org/artists/141"); RDFResource mariobotta = new RDFResource("http://example.org/artists/696"); RDFResource louisikahn = new RDFResource("http://example.org/artists/2964"); RDFResource frederickkiesler = new RDFResource("http://example.org/artists/3091"); RDFResource leonkrier = new RDFResource("http://example.org/artists/3250"); RDFResource masayukikurokawa = new RDFResource("http://example.org/artists/3308"); RDFResource ernestobrunolapadula = new RDFResource("http://example.org/artists/3381"); RDFResource richardmeier = new RDFResource("http://example.org/artists/3910"); RDFResource eerosaarinen = new RDFResource("http://example.org/artists/5103"); RDFResource franklloydwright = new RDFResource("http://example.org/artists/6459"); RDFResource evazeisel = new RDFResource("http://example.org/artists/6556"); RDFResource zahahadid = new RDFResource("http://example.org/artists/6953"); RDFResource santiagocalatrava = new RDFResource("http://example.org/artists/6968"); RDFResource tadaoando = new RDFResource("http://example.org/artists/7055"); RDFResource ludwigmiesvanderrohe = new RDFResource("http://example.org/artists/7166"); RDFResource rafaelviñoly = new RDFResource("http://example.org/artists/7229"); RDFResource aldorossi = new RDFResource("http://example.org/artists/7661"); RDFResource simonungers = new RDFResource("http://example.org/artists/7992"); RDFResource giovanniguerrini = new RDFResource("http://example.org/artists/8157"); RDFResource marioromano = new RDFResource("http://example.org/artists/8158"); RDFResource thommayne = new RDFResource("http://example.org/artists/8218"); RDFResource thomaskinslow = new RDFResource("http://example.org/artists/8248"); RDFResource fusogomuindcoltdtokyo = new RDFResource("http://example.org/artists/9029"); RDFResource hallchinacoeastliverpooloh = new RDFResource("http://example.org/artists/10013"); RDFResource andrewzago = new RDFResource("http://example.org/artists/22884"); RDFResource morphosissantamonicaca = new RDFResource("http://example.org/artists/29711"); // Artists(agents): plain literal name RDFPlainLiteral aldorossiName = new RDFPlainLiteral("Aldo Rossi"); RDFPlainLiteral andrewzagoName = new RDFPlainLiteral("Andrew Zago"); RDFPlainLiteral eerosaarinenName = new RDFPlainLiteral("Eero Saarinen"); RDFPlainLiteral emilioambaszName = new RDFPlainLiteral("Emilio Ambasz"); RDFPlainLiteral ernestobrunolapadulaName = new RDFPlainLiteral("Ernesto Bruno La Padula"); RDFPlainLiteral evazeiselName = new RDFPlainLiteral("Eva Zeisel"); RDFPlainLiteral franklloydwrightName = new RDFPlainLiteral("Frank Lloyd Wright"); RDFPlainLiteral frederickkieslerName = new RDFPlainLiteral("Frederick Kiesler"); RDFPlainLiteral fusogomuindcoltdtokyoName = new RDFPlainLiteral("Fuso Gomu Ind. Co., Ltd., Tokyo"); RDFPlainLiteral giovanniguerriniName = new RDFPlainLiteral("Giovanni Guerrini"); RDFPlainLiteral hallchinacoeastliverpoolohName = new RDFPlainLiteral("Hall China Co., East Liverpool, OH"); RDFPlainLiteral leonkrierName = new RDFPlainLiteral("Leon Krier"); RDFPlainLiteral louisikahnName = new RDFPlainLiteral("Louis I. Kahn"); RDFPlainLiteral ludwigmiesvanderroheName = new RDFPlainLiteral("Ludwig Mies van der Rohe"); RDFPlainLiteral mariobottaName = new RDFPlainLiteral("Mario Botta"); RDFPlainLiteral marioromanoName = new RDFPlainLiteral("Mario Romano"); RDFPlainLiteral masayukikurokawaName = new RDFPlainLiteral("Masayuki Kurokawa"); RDFPlainLiteral morphosissantamonicacaName = new RDFPlainLiteral("Morphosis, Santa Monica, CA"); RDFPlainLiteral rafaelviñolyName = new RDFPlainLiteral("Rafael Viñoly"); RDFPlainLiteral raimundabrahamName = new RDFPlainLiteral("Raimund Abraham"); RDFPlainLiteral richardmeierName = new RDFPlainLiteral("Richard Meier"); RDFPlainLiteral santiagocalatravaName = new RDFPlainLiteral("Santiago Calatrava"); RDFPlainLiteral simonungersName = new RDFPlainLiteral("Simon Ungers"); RDFPlainLiteral tadaoandoName = new RDFPlainLiteral("Tadao Ando"); RDFPlainLiteral thommayneName = new RDFPlainLiteral("Thom Mayne"); RDFPlainLiteral thomaskinslowName = new RDFPlainLiteral("Thomas Kinslow"); RDFPlainLiteral zahahadidName = new RDFPlainLiteral("Zaha Hadid"); #endregion #region Locations (tgn) RDFResource northwales = new RDFResource("http://vocab.getty.edu/tgn/2091433-place"); RDFResource wales = new RDFResource("http://vocab.getty.edu/tgn/7002443-place"); RDFResource berlin = new RDFResource("http://vocab.getty.edu/tgn/7003712-place"); RDFResource newyork = new RDFResource("http://vocab.getty.edu/tgn/7007567-place"); RDFResource edinburgh = new RDFResource("http://vocab.getty.edu/tgn/7009546-place"); RDFResource kiyev = new RDFResource("http://vocab.getty.edu/tgn/7010171-place"); RDFResource london = new RDFResource("http://vocab.getty.edu/tgn/7011781-place"); RDFResource moskva = new RDFResource("http://vocab.getty.edu/tgn/7012974-place"); RDFResource boston = new RDFResource("http://vocab.getty.edu/tgn/7013445-place"); RDFResource detroit = new RDFResource("http://vocab.getty.edu/tgn/7013547-place"); RDFResource longbeach = new RDFResource("http://vocab.getty.edu/tgn/7013905-place"); RDFResource sanfrancisco = new RDFResource("http://vocab.getty.edu/tgn/7014456-place"); // Locations (tgn): plain literal name RDFPlainLiteral berlinName = new RDFPlainLiteral("Berlin"); RDFPlainLiteral bostonName = new RDFPlainLiteral("Boston"); RDFPlainLiteral detroitName = new RDFPlainLiteral("Detroit"); RDFPlainLiteral edinburghName = new RDFPlainLiteral("Edinburgh"); RDFPlainLiteral kiyevName = new RDFPlainLiteral("Kiyev"); RDFPlainLiteral londonName = new RDFPlainLiteral("London"); RDFPlainLiteral longbeachName = new RDFPlainLiteral("Long Beach"); RDFPlainLiteral moskvaName = new RDFPlainLiteral("Moskva"); RDFPlainLiteral newyorkName = new RDFPlainLiteral("New York"); RDFPlainLiteral northwalesName = new RDFPlainLiteral("North Wales"); RDFPlainLiteral sanfranciscoName = new RDFPlainLiteral("San Francisco"); RDFPlainLiteral walesName = new RDFPlainLiteral("Wales"); #endregion #region Triples // Create triple resources RDFTriple aldorossi_type_agent = new RDFTriple(aldorossi, type, agent); RDFTriple andrewzago_type_agent = new RDFTriple(andrewzago, type, agent); RDFTriple eerosaarinen_type_agent = new RDFTriple(eerosaarinen, type, agent); RDFTriple emilioambasz_type_agent = new RDFTriple(emilioambasz, type, agent); RDFTriple ernestobrunolapadula_type_agent = new RDFTriple(ernestobrunolapadula, type, agent); RDFTriple evazeisel_type_agent = new RDFTriple(evazeisel, type, agent); RDFTriple franklloydwright_type_agent = new RDFTriple(franklloydwright, type, agent); RDFTriple frederickkiesler_type_agent = new RDFTriple(frederickkiesler, type, agent); RDFTriple fusogomuindcoltdtokyo_type_agent = new RDFTriple(fusogomuindcoltdtokyo, type, agent); RDFTriple giovanniguerrini_type_agent = new RDFTriple(giovanniguerrini, type, agent); RDFTriple hallchinacoeastliverpooloh_type_agent = new RDFTriple(hallchinacoeastliverpooloh, type, agent); RDFTriple leonkrier_type_agent = new RDFTriple(leonkrier, type, agent); RDFTriple louisikahn_type_agent = new RDFTriple(louisikahn, type, agent); RDFTriple ludwigmiesvanderrohe_type_agent = new RDFTriple(ludwigmiesvanderrohe, type, agent); RDFTriple mariobotta_type_agent = new RDFTriple(mariobotta, type, agent); RDFTriple marioromano_type_agent = new RDFTriple(marioromano, type, agent); RDFTriple masayukikurokawa_type_agent = new RDFTriple(masayukikurokawa, type, agent); RDFTriple morphosissantamonicaca_type_agent = new RDFTriple(morphosissantamonicaca, type, agent); RDFTriple rafaelviñoly_type_agent = new RDFTriple(rafaelviñoly, type, agent); RDFTriple raimundabraham_type_agent = new RDFTriple(raimundabraham, type, agent); RDFTriple richardmeier_type_agent = new RDFTriple(richardmeier, type, agent); RDFTriple santiagocalatrava_type_agent = new RDFTriple(santiagocalatrava, type, agent); RDFTriple simonungers_type_agent = new RDFTriple(simonungers, type, agent); RDFTriple tadaoando_type_agent = new RDFTriple(tadaoando, type, agent); RDFTriple thommayne_type_agent = new RDFTriple(thommayne, type, agent); RDFTriple thomaskinslow_type_agent = new RDFTriple(thomaskinslow, type, agent); RDFTriple zahahadid_type_agent = new RDFTriple(zahahadid, type, agent); RDFTriple berlin_type_tgn = new RDFTriple(berlin, type, tgn); RDFTriple boston_type_tgn = new RDFTriple(boston, type, tgn); RDFTriple detroit_type_tgn = new RDFTriple(detroit, type, tgn); RDFTriple edinburgh_type_tgn = new RDFTriple(edinburgh, type, tgn); RDFTriple kiyev_type_tgn = new RDFTriple(kiyev, type, tgn); RDFTriple london_type_tgn = new RDFTriple(london, type, tgn); RDFTriple longbeach_type_tgn = new RDFTriple(longbeach, type, tgn); RDFTriple moskva_type_tgn = new RDFTriple(moskva, type, tgn); RDFTriple newyork_type_tgn = new RDFTriple(newyork, type, tgn); RDFTriple northwales_type_tgn = new RDFTriple(northwales, type, tgn); RDFTriple sanfrancisco_type_tgn = new RDFTriple(sanfrancisco, type, tgn); RDFTriple wales_type_tgn = new RDFTriple(wales, type, tgn); RDFTriple aldorossi_name_aldorossiName = new RDFTriple(aldorossi, name, aldorossiName); RDFTriple andrewzago_name_andrewzagoName = new RDFTriple(andrewzago, name, andrewzagoName); RDFTriple eerosaarinen_name_eerosaarinenName = new RDFTriple(eerosaarinen, name, eerosaarinenName); RDFTriple emilioambasz_name_emilioambaszName = new RDFTriple(emilioambasz, name, emilioambaszName); RDFTriple ernestobrunolapadula_name_ernestobrunolapadulaName = new RDFTriple(ernestobrunolapadula, name, ernestobrunolapadulaName); RDFTriple evazeisel_name_evazeiselName = new RDFTriple(evazeisel, name, evazeiselName); RDFTriple franklloydwright_name_franklloydwrightName = new RDFTriple(franklloydwright, name, franklloydwrightName); RDFTriple frederickkiesler_name_frederickkieslerName = new RDFTriple(frederickkiesler, name, frederickkieslerName); RDFTriple fusogomuindcoltdtokyo_name_fusogomuindcoltdtokyoName = new RDFTriple(fusogomuindcoltdtokyo, name, fusogomuindcoltdtokyoName); RDFTriple giovanniguerrini_name_giovanniguerriniName = new RDFTriple(giovanniguerrini, name, giovanniguerriniName); RDFTriple hallchinacoeastliverpooloh_name_hallchinacoeastliverpoolohName = new RDFTriple(hallchinacoeastliverpooloh, name, hallchinacoeastliverpoolohName); RDFTriple leonkrier_name_leonkrierName = new RDFTriple(leonkrier, name, leonkrierName); RDFTriple louisikahn_name_louisikahnName = new RDFTriple(louisikahn, name, louisikahnName); RDFTriple ludwigmiesvanderrohe_name_ludwigmiesvanderroheName = new RDFTriple(ludwigmiesvanderrohe, name, ludwigmiesvanderroheName); RDFTriple mariobotta_name_mariobottaName = new RDFTriple(mariobotta, name, mariobottaName); RDFTriple marioromano_name_marioromanoName = new RDFTriple(marioromano, name, marioromanoName); RDFTriple masayukikurokawa_name_masayukikurokawaName = new RDFTriple(masayukikurokawa, name, masayukikurokawaName); RDFTriple morphosissantamonicaca_name_morphosissantamonicacaName = new RDFTriple(morphosissantamonicaca, name, morphosissantamonicacaName); RDFTriple rafaelviñoly_name_rafaelviñolyName = new RDFTriple(rafaelviñoly, name, rafaelviñolyName); RDFTriple raimundabraham_name_raimundabrahamName = new RDFTriple(raimundabraham, name, raimundabrahamName); RDFTriple richardmeier_name_richardmeierName = new RDFTriple(richardmeier, name, richardmeierName); RDFTriple santiagocalatrava_name_santiagocalatravaName = new RDFTriple(santiagocalatrava, name, santiagocalatravaName); RDFTriple simonungers_name_simonungersName = new RDFTriple(simonungers, name, simonungersName); RDFTriple tadaoando_name_tadaoandoName = new RDFTriple(tadaoando, name, tadaoandoName); RDFTriple thommayne_name_thommayneName = new RDFTriple(thommayne, name, thommayneName); RDFTriple thomaskinslow_name_thomaskinslowName = new RDFTriple(thomaskinslow, name, thomaskinslowName); RDFTriple zahahadid_name_zahahadidName = new RDFTriple(zahahadid, name, zahahadidName); RDFTriple berlin_name_berlinName = new RDFTriple(berlin, name, berlinName); RDFTriple boston_name_bostonName = new RDFTriple(boston, name, bostonName); RDFTriple detroit_name_detroitName = new RDFTriple(detroit, name, detroitName); RDFTriple edinburgh_name_edinburghName = new RDFTriple(edinburgh, name, edinburghName); RDFTriple kiyev_name_kiyevName = new RDFTriple(kiyev, name, kiyevName); RDFTriple london_name_londonName = new RDFTriple(london, name, londonName); RDFTriple longbeach_name_longbeachName = new RDFTriple(longbeach, name, longbeachName); RDFTriple moskva_name_moskvaName = new RDFTriple(moskva, name, moskvaName); RDFTriple newyork_name_newyorkName = new RDFTriple(newyork, name, newyorkName); RDFTriple northwales_name_northwalesName = new RDFTriple(northwales, name, northwalesName); RDFTriple sanfrancisco_name_sanfranciscoName = new RDFTriple(sanfrancisco, name, sanfranciscoName); RDFTriple wales_name_walesName = new RDFTriple(wales, name, walesName); RDFTriple aldorossi_activeIn_moskva = new RDFTriple(aldorossi, activeIn, moskva); RDFTriple andrewzago_activeIn_moskva = new RDFTriple(andrewzago, activeIn, moskva); RDFTriple eerosaarinen_activeIn_newyork = new RDFTriple(eerosaarinen, activeIn, newyork); RDFTriple emilioambasz_activeIn_newyork = new RDFTriple(emilioambasz, activeIn, newyork); RDFTriple ernestobrunolapadula_activeIn_newyork = new RDFTriple(ernestobrunolapadula, activeIn, newyork); RDFTriple evazeisel_educatedIn_berlin = new RDFTriple(evazeisel, educatedIn, berlin); RDFTriple franklloydwright_activeIn_detroit = new RDFTriple(franklloydwright, activeIn, detroit); RDFTriple franklloydwright_livedIn_moskva = new RDFTriple(franklloydwright, livedIn, moskva); RDFTriple frederickkiesler_livedIn_longbeach = new RDFTriple(frederickkiesler, livedIn, longbeach); RDFTriple fusogomuindcoltdtokyo_livedIn_london = new RDFTriple(fusogomuindcoltdtokyo, livedIn, london); RDFTriple giovanniguerrini_activeIn_newyork = new RDFTriple(giovanniguerrini, activeIn, newyork); RDFTriple hallchinacoeastliverpooloh_educatedIn_berlin = new RDFTriple(hallchinacoeastliverpooloh, educatedIn, berlin); RDFTriple leonkrier_activeIn_newyork = new RDFTriple(leonkrier, activeIn, newyork); RDFTriple leonkrier_educatedIn_london = new RDFTriple(leonkrier, educatedIn, london); RDFTriple louisikahn_livedIn_longbeach = new RDFTriple(louisikahn, livedIn, longbeach); RDFTriple louisikahn_livedIn_newyork = new RDFTriple(louisikahn, livedIn, newyork); RDFTriple ludwigmiesvanderrohe_activeIn_moskva = new RDFTriple(ludwigmiesvanderrohe, activeIn, moskva); RDFTriple ludwigmiesvanderrohe_livedIn_moskva = new RDFTriple(ludwigmiesvanderrohe, livedIn, moskva); RDFTriple mariobotta_activeIn_kiyev = new RDFTriple(mariobotta, activeIn, kiyev); RDFTriple mariobotta_activeIn_moskva = new RDFTriple(mariobotta, activeIn, moskva); RDFTriple mariobotta_livedIn_moskva = new RDFTriple(mariobotta, livedIn, moskva); RDFTriple marioromano_activeIn_newyork = new RDFTriple(marioromano, activeIn, newyork); RDFTriple masayukikurokawa_livedIn_london = new RDFTriple(masayukikurokawa, livedIn, london); RDFTriple morphosissantamonicaca_activeIn_moskva = new RDFTriple(morphosissantamonicaca, activeIn, moskva); RDFTriple rafaelviñoly_activeIn_newyork = new RDFTriple(rafaelviñoly, activeIn, newyork); RDFTriple raimundabraham_livedIn_moskva = new RDFTriple(raimundabraham, livedIn, moskva); RDFTriple richardmeier_activeIn_edinburgh = new RDFTriple(richardmeier, activeIn, edinburgh); RDFTriple richardmeier_activeIn_london = new RDFTriple(richardmeier, activeIn, london); RDFTriple richardmeier_educatedIn_london = new RDFTriple(richardmeier, educatedIn, london); RDFTriple santiagocalatrava_livedIn_newyork = new RDFTriple(santiagocalatrava, livedIn, newyork); RDFTriple simonungers_livedIn_boston = new RDFTriple(simonungers, livedIn, boston); RDFTriple simonungers_livedIn_newyork = new RDFTriple(simonungers, livedIn, newyork); RDFTriple tadaoando_activeIn_newyork = new RDFTriple(tadaoando, activeIn, newyork); RDFTriple tadaoando_livedIn_northwales = new RDFTriple(tadaoando, livedIn, northwales); RDFTriple tadaoando_livedIn_wales = new RDFTriple(tadaoando, livedIn, wales); RDFTriple thommayne_activeIn_moskva = new RDFTriple(thommayne, activeIn, moskva); RDFTriple thomaskinslow_livedIn_boston = new RDFTriple(thomaskinslow, livedIn, boston); RDFTriple thomaskinslow_livedIn_newyork = new RDFTriple(thomaskinslow, livedIn, newyork); RDFTriple zahahadid_activeIn_sanfrancisco = new RDFTriple(zahahadid, activeIn, sanfrancisco); #endregion #region Add triples to graph RDFGraph m_graph = new RDFGraph(); m_graph.AddTriple(aldorossi_activeIn_moskva); m_graph.AddTriple(aldorossi_name_aldorossiName); m_graph.AddTriple(aldorossi_type_agent); m_graph.AddTriple(andrewzago_activeIn_moskva); m_graph.AddTriple(andrewzago_name_andrewzagoName); m_graph.AddTriple(andrewzago_type_agent); m_graph.AddTriple(berlin_name_berlinName); m_graph.AddTriple(berlin_type_tgn); m_graph.AddTriple(boston_name_bostonName); m_graph.AddTriple(boston_type_tgn); m_graph.AddTriple(detroit_name_detroitName); m_graph.AddTriple(detroit_type_tgn); m_graph.AddTriple(edinburgh_name_edinburghName); m_graph.AddTriple(edinburgh_type_tgn); m_graph.AddTriple(eerosaarinen_activeIn_newyork); m_graph.AddTriple(eerosaarinen_name_eerosaarinenName); m_graph.AddTriple(eerosaarinen_type_agent); m_graph.AddTriple(emilioambasz_activeIn_newyork); m_graph.AddTriple(emilioambasz_name_emilioambaszName); m_graph.AddTriple(emilioambasz_type_agent); m_graph.AddTriple(ernestobrunolapadula_activeIn_newyork); m_graph.AddTriple(ernestobrunolapadula_name_ernestobrunolapadulaName); m_graph.AddTriple(ernestobrunolapadula_type_agent); m_graph.AddTriple(evazeisel_educatedIn_berlin); m_graph.AddTriple(evazeisel_name_evazeiselName); m_graph.AddTriple(evazeisel_type_agent); m_graph.AddTriple(franklloydwright_activeIn_detroit); m_graph.AddTriple(franklloydwright_livedIn_moskva); m_graph.AddTriple(franklloydwright_name_franklloydwrightName); m_graph.AddTriple(franklloydwright_type_agent); m_graph.AddTriple(frederickkiesler_livedIn_longbeach); m_graph.AddTriple(frederickkiesler_name_frederickkieslerName); m_graph.AddTriple(frederickkiesler_type_agent); m_graph.AddTriple(fusogomuindcoltdtokyo_livedIn_london); m_graph.AddTriple(fusogomuindcoltdtokyo_name_fusogomuindcoltdtokyoName); m_graph.AddTriple(fusogomuindcoltdtokyo_type_agent); m_graph.AddTriple(giovanniguerrini_activeIn_newyork); m_graph.AddTriple(giovanniguerrini_name_giovanniguerriniName); m_graph.AddTriple(giovanniguerrini_type_agent); m_graph.AddTriple(hallchinacoeastliverpooloh_educatedIn_berlin); m_graph.AddTriple(hallchinacoeastliverpooloh_name_hallchinacoeastliverpoolohName); m_graph.AddTriple(hallchinacoeastliverpooloh_type_agent); m_graph.AddTriple(kiyev_name_kiyevName); m_graph.AddTriple(kiyev_type_tgn); m_graph.AddTriple(leonkrier_activeIn_newyork); m_graph.AddTriple(leonkrier_educatedIn_london); m_graph.AddTriple(leonkrier_name_leonkrierName); m_graph.AddTriple(leonkrier_type_agent); m_graph.AddTriple(london_name_londonName); m_graph.AddTriple(london_type_tgn); m_graph.AddTriple(longbeach_name_longbeachName); m_graph.AddTriple(longbeach_type_tgn); m_graph.AddTriple(louisikahn_livedIn_longbeach); m_graph.AddTriple(louisikahn_livedIn_newyork); m_graph.AddTriple(louisikahn_name_louisikahnName); m_graph.AddTriple(louisikahn_type_agent); m_graph.AddTriple(ludwigmiesvanderrohe_activeIn_moskva); m_graph.AddTriple(ludwigmiesvanderrohe_livedIn_moskva); m_graph.AddTriple(ludwigmiesvanderrohe_name_ludwigmiesvanderroheName); m_graph.AddTriple(ludwigmiesvanderrohe_type_agent); m_graph.AddTriple(mariobotta_activeIn_kiyev); m_graph.AddTriple(mariobotta_activeIn_moskva); m_graph.AddTriple(mariobotta_livedIn_moskva); m_graph.AddTriple(mariobotta_name_mariobottaName); m_graph.AddTriple(mariobotta_type_agent); m_graph.AddTriple(marioromano_activeIn_newyork); m_graph.AddTriple(marioromano_name_marioromanoName); m_graph.AddTriple(marioromano_type_agent); m_graph.AddTriple(masayukikurokawa_livedIn_london); m_graph.AddTriple(masayukikurokawa_name_masayukikurokawaName); m_graph.AddTriple(masayukikurokawa_type_agent); m_graph.AddTriple(morphosissantamonicaca_activeIn_moskva); m_graph.AddTriple(morphosissantamonicaca_name_morphosissantamonicacaName); m_graph.AddTriple(morphosissantamonicaca_type_agent); m_graph.AddTriple(moskva_name_moskvaName); m_graph.AddTriple(moskva_type_tgn); m_graph.AddTriple(newyork_name_newyorkName); m_graph.AddTriple(newyork_type_tgn); m_graph.AddTriple(northwales_name_northwalesName); m_graph.AddTriple(northwales_type_tgn); m_graph.AddTriple(rafaelviñoly_activeIn_newyork); m_graph.AddTriple(rafaelviñoly_name_rafaelviñolyName); m_graph.AddTriple(rafaelviñoly_type_agent); m_graph.AddTriple(raimundabraham_livedIn_moskva); m_graph.AddTriple(raimundabraham_name_raimundabrahamName); m_graph.AddTriple(raimundabraham_type_agent); m_graph.AddTriple(richardmeier_activeIn_edinburgh); m_graph.AddTriple(richardmeier_activeIn_london); m_graph.AddTriple(richardmeier_educatedIn_london); m_graph.AddTriple(richardmeier_name_richardmeierName); m_graph.AddTriple(richardmeier_type_agent); m_graph.AddTriple(sanfrancisco_name_sanfranciscoName); m_graph.AddTriple(sanfrancisco_type_tgn); m_graph.AddTriple(santiagocalatrava_livedIn_newyork); m_graph.AddTriple(santiagocalatrava_name_santiagocalatravaName); m_graph.AddTriple(santiagocalatrava_type_agent); m_graph.AddTriple(simonungers_livedIn_boston); m_graph.AddTriple(simonungers_livedIn_newyork); m_graph.AddTriple(simonungers_name_simonungersName); m_graph.AddTriple(simonungers_type_agent); m_graph.AddTriple(tadaoando_activeIn_newyork); m_graph.AddTriple(tadaoando_livedIn_northwales); m_graph.AddTriple(tadaoando_livedIn_wales); m_graph.AddTriple(tadaoando_name_tadaoandoName); m_graph.AddTriple(tadaoando_type_agent); m_graph.AddTriple(thomaskinslow_livedIn_boston); m_graph.AddTriple(thomaskinslow_livedIn_newyork); m_graph.AddTriple(thomaskinslow_name_thomaskinslowName); m_graph.AddTriple(thomaskinslow_type_agent); m_graph.AddTriple(thommayne_activeIn_moskva); m_graph.AddTriple(thommayne_name_thommayneName); m_graph.AddTriple(thommayne_type_agent); m_graph.AddTriple(wales_name_walesName); m_graph.AddTriple(wales_type_tgn); m_graph.AddTriple(zahahadid_activeIn_sanfrancisco); m_graph.AddTriple(zahahadid_name_zahahadidName); m_graph.AddTriple(zahahadid_type_agent); #endregion // Only using RdfXml for this example so no need to write/read all files // Write RDF RDFSerializer.WriteRDF(RDFModelEnums.RDFFormats.RdfXml, m_graph, Server.MapPath("~/").ToString() + "\\" + "tms.rdf"); //RDFSerializer.WriteRDF(RDFModelEnums.RDFFormats.Turtle, m_graph, Server.MapPath("~/").ToString() + "\\" + "\\tms.ttl"); //RDFSerializer.WriteRDF(RDFModelEnums.RDFFormats.TriX, m_graph, Server.MapPath("~/").ToString() + "\\" + "\\tms.trix"); //RDFSerializer.WriteRDF(RDFModelEnums.RDFFormats.NTriples, m_graph, Server.MapPath("~/").ToString() + "\\" + "\\tms.nt"); // Read RDF RDFGraph tmsRDF = RDFSerializer.ReadRDF(RDFModelEnums.RDFFormats.RdfXml, Server.MapPath("~/").ToString() + "\\tms.rdf"); //RDFGraph tmsTURTLE = RDFSerializer.ReadRDF(RDFModelEnums.RDFFormats.Turtle, Environment.CurrentDirectory + "\\tms.ttl"); //RDFGraph tmsTRIX = RDFSerializer.ReadRDF(RDFModelEnums.RDFFormats.TriX, Environment.CurrentDirectory + "\\tms.trix"); //RDFGraph tmsNT = RDFSerializer.ReadRDF(RDFModelEnums.RDFFormats.NTriples, Environment.CurrentDirectory + "\\tms.nt"); // Write the RDF into SQL Server. You have other choices with RDFSharp including RDFMemoryStore string m_conn = ConfigurationManager.ConnectionStrings["RDFConnectionString"].ConnectionString; RDFSQLServerStore rdf_mssql = new RDFSQLServerStore(m_conn); rdf_mssql.MergeGraph(tmsRDF); // At this point you can open SQL Server and see a new table called Quadruples with all of the data in the correct format. // The first time you run this (successfully), the RdfViewer.aspx page will be empty. // Uncomment GetRDF() above and comment LoadRDF() and you should see a datagrid with RDF data. }
/// <summary> /// Serializes the given graph to the given stream using XML data format. /// </summary> internal static void Serialize(RDFGraph graph, Stream outputStream) { try { #region serialize using (XmlTextWriter rdfxmlWriter = new XmlTextWriter(outputStream, Encoding.UTF8)) { XmlDocument rdfDoc = new XmlDocument(); rdfxmlWriter.Formatting = Formatting.Indented; #region xmlDecl XmlDeclaration xmlDecl = rdfDoc.CreateXmlDeclaration("1.0", "UTF-8", null); rdfDoc.AppendChild(xmlDecl); #endregion #region rdfRoot XmlNode rdfRoot = rdfDoc.CreateNode(XmlNodeType.Element, RDFVocabulary.RDF.PREFIX + ":RDF", RDFVocabulary.RDF.BASE_URI); XmlAttribute rdfRootNS = rdfDoc.CreateAttribute("xmlns:" + RDFVocabulary.RDF.PREFIX); XmlText rdfRootNSText = rdfDoc.CreateTextNode(RDFVocabulary.RDF.BASE_URI); rdfRootNS.AppendChild(rdfRootNSText); rdfRoot.Attributes.Append(rdfRootNS); #region prefixes //Write the graph's prefixes (except for "rdf", which has already been written) graph.GraphMetadata.Namespaces.ForEach(p => { if (!p.Prefix.Equals(RDFVocabulary.RDF.PREFIX, StringComparison.Ordinal) && !p.Prefix.Equals("base", StringComparison.Ordinal)) { XmlAttribute pfRootNS = rdfDoc.CreateAttribute("xmlns:" + p.Prefix); XmlText pfRootNSText = rdfDoc.CreateTextNode(p.ToString()); pfRootNS.AppendChild(pfRootNSText); rdfRoot.Attributes.Append(pfRootNS); } }); //Write the graph's base uri to resolve eventual relative #IDs XmlAttribute pfBaseNS = rdfDoc.CreateAttribute(RDFVocabulary.XML.PREFIX + ":base"); XmlText pfBaseNSText = rdfDoc.CreateTextNode(graph.Context.ToString()); pfBaseNS.AppendChild(pfBaseNSText); rdfRoot.Attributes.Append(pfBaseNS); #endregion #region linq //Group the graph's triples by subj var groupedList = (from triple in graph orderby triple.Subject.ToString() group triple by new { subj = triple.Subject.ToString() }); #endregion #region graph //Iterate over the calculated groups Dictionary <RDFResource, XmlNode> containers = new Dictionary <RDFResource, XmlNode>(); //Floating containers have reification subject which is never object of any graph's triple Boolean floatingContainers = graph.GraphMetadata.Containers.Keys.Any(k => graph.Triples.Values.Count(v => v.Object.Equals(k)) == 0); //Floating collections have reification subject which is never object of any graph's triple Boolean floatingCollections = graph.GraphMetadata.Collections.Keys.Any(k => graph.Triples.Values.Count(v => v.Object.Equals(k)) == 0); foreach (var group in groupedList) { #region subj //Check if the current subj is a container or a collection subj: if so it must be //serialized in the canonical RDF/XML way instead of the "rdf:Description" way XmlNode subjNode = null; String subj = group.Key.subj; //It is a container subj, so add it to the containers pool if (graph.GraphMetadata.Containers.Keys.Any(k => k.ToString().Equals(subj, StringComparison.Ordinal)) && !floatingContainers) { switch (graph.GraphMetadata.Containers.Single(c => c.Key.ToString().Equals(subj, StringComparison.Ordinal)).Value) { case RDFModelEnums.RDFContainerType.Bag: subjNode = rdfDoc.CreateNode(XmlNodeType.Element, RDFVocabulary.RDF.PREFIX + ":Bag", RDFVocabulary.RDF.BASE_URI); containers.Add(new RDFResource(subj), subjNode); break; case RDFModelEnums.RDFContainerType.Seq: subjNode = rdfDoc.CreateNode(XmlNodeType.Element, RDFVocabulary.RDF.PREFIX + ":Seq", RDFVocabulary.RDF.BASE_URI); containers.Add(new RDFResource(subj), subjNode); break; case RDFModelEnums.RDFContainerType.Alt: subjNode = rdfDoc.CreateNode(XmlNodeType.Element, RDFVocabulary.RDF.PREFIX + ":Alt", RDFVocabulary.RDF.BASE_URI); containers.Add(new RDFResource(subj), subjNode); break; } } //It is a subj of a collection of resources, so do not append triples having it as a subject //because we will reconstruct the collection and append it as a whole else if (graph.GraphMetadata.Collections.Keys.Any(k => k.ToString().Equals(subj, StringComparison.Ordinal)) && graph.GraphMetadata.Collections.Single(c => c.Key.ToString().Equals(subj, StringComparison.Ordinal)).Value.ItemType == RDFModelEnums.RDFItemType.Resource && !floatingCollections) { continue; } //It is neither a container or a collection subj else { subjNode = rdfDoc.CreateNode(XmlNodeType.Element, RDFVocabulary.RDF.PREFIX + ":Description", RDFVocabulary.RDF.BASE_URI); //<rdf:Description rdf:nodeID="blankID"> XmlAttribute subjNodeDesc = null; XmlText subjNodeDescText = rdfDoc.CreateTextNode(group.Key.subj); if (group.Key.subj.StartsWith("bnode:")) { subjNodeDescText.InnerText = subjNodeDescText.InnerText.Replace("bnode:", String.Empty); subjNodeDesc = rdfDoc.CreateAttribute(RDFVocabulary.RDF.PREFIX + ":nodeID", RDFVocabulary.RDF.BASE_URI); } //<rdf:Description rdf:about="subjURI"> else { subjNodeDesc = rdfDoc.CreateAttribute(RDFVocabulary.RDF.PREFIX + ":about", RDFVocabulary.RDF.BASE_URI); } subjNodeDesc.AppendChild(subjNodeDescText); subjNode.Attributes.Append(subjNodeDesc); } #endregion #region predObjList //Iterate over the triples of the current group foreach (var triple in group) { //Do not append the triple if it is "SUBJECT rdf:type rdf:[Bag|Seq|Alt]" if (!(triple.Predicate.Equals(RDFVocabulary.RDF.TYPE) && (subjNode.Name.Equals(RDFVocabulary.RDF.PREFIX + ":Bag", StringComparison.Ordinal) || subjNode.Name.Equals(RDFVocabulary.RDF.PREFIX + ":Seq", StringComparison.Ordinal) || subjNode.Name.Equals(RDFVocabulary.RDF.PREFIX + ":Alt", StringComparison.Ordinal)))) { #region pred String predString = triple.Predicate.ToString(); //"<predPREF:predURI" RDFNamespace predNS = (RDFNamespaceRegister.GetByNamespace(predString) ?? RDFModelUtilities.GenerateNamespace(predString, false)); //Refine the pred with eventually necessary sanitizations String predUri = predString.Replace(predNS.ToString(), predNS.Prefix + ":") .Replace(":#", ":") .TrimEnd(new Char[] { ':', '/' }); //Sanitize eventually detected automatic namespace if (predUri.StartsWith("autoNS:")) { predUri = predUri.Replace("autoNS:", string.Empty); } //Do not write "xmlns" attribute if the predUri is the context of the graph XmlNode predNode = null; if (predNS.ToString().Equals(graph.Context.ToString(), StringComparison.Ordinal)) { predNode = rdfDoc.CreateNode(XmlNodeType.Element, predUri, null); } else { predNode = rdfDoc.CreateNode(XmlNodeType.Element, predUri, predNS.ToString()); } #endregion #region object if (triple.TripleFlavor == RDFModelEnums.RDFTripleFlavor.SPO) { //If the object is a container subj, we must append its entire node saved in the containers dictionary if (containers.Keys.Any(k => k.Equals(triple.Object)) && !floatingContainers) { predNode.AppendChild(containers.Single(c => c.Key.Equals(triple.Object)).Value); } //Else, if the object is a subject of a collection of resources, we must append the "rdf:parseType=Collection" attribute to the predicate node else if (graph.GraphMetadata.Collections.Keys.Any(k => k.Equals(triple.Object)) && graph.GraphMetadata.Collections.Single(c => c.Key.Equals(triple.Object)).Value.ItemType == RDFModelEnums.RDFItemType.Resource && !floatingCollections) { XmlAttribute rdfParseType = rdfDoc.CreateAttribute(RDFVocabulary.RDF.PREFIX + ":parseType", RDFVocabulary.RDF.BASE_URI); XmlText rdfParseTypeText = rdfDoc.CreateTextNode("Collection"); rdfParseType.AppendChild(rdfParseTypeText); predNode.Attributes.Append(rdfParseType); //Then we append sequentially the collection elements List <XmlNode> collElements = ReconstructCollection(graph.GraphMetadata, (RDFResource)triple.Object, rdfDoc); collElements.ForEach(c => predNode.AppendChild(c)); } //Else, threat it as a traditional object node else { String objString = triple.Object.ToString(); XmlAttribute predNodeDesc = null; XmlText predNodeDescText = rdfDoc.CreateTextNode(objString); // rdf:nodeID="blankID"> if (objString.StartsWith("bnode:")) { predNodeDescText.InnerText = predNodeDescText.InnerText.Replace("bnode:", String.Empty); predNodeDesc = rdfDoc.CreateAttribute(RDFVocabulary.RDF.PREFIX + ":nodeID", RDFVocabulary.RDF.BASE_URI); } // rdf:resource="objURI"> else { predNodeDesc = rdfDoc.CreateAttribute(RDFVocabulary.RDF.PREFIX + ":resource", RDFVocabulary.RDF.BASE_URI); } predNodeDesc.AppendChild(predNodeDescText); predNode.Attributes.Append(predNodeDesc); } } #endregion #region literal else { #region plain literal if (triple.Object is RDFPlainLiteral) { RDFPlainLiteral pLit = (RDFPlainLiteral)triple.Object; // xml:lang="plitLANG"> if (pLit.Language != String.Empty) { XmlAttribute plainLiteralLangNodeDesc = rdfDoc.CreateAttribute(RDFVocabulary.XML.PREFIX + ":lang", RDFVocabulary.XML.BASE_URI); XmlText plainLiteralLangNodeDescText = rdfDoc.CreateTextNode(pLit.Language); plainLiteralLangNodeDesc.AppendChild(plainLiteralLangNodeDescText); predNode.Attributes.Append(plainLiteralLangNodeDesc); } } #endregion #region typed literal // rdf:datatype="tlitURI"> else { RDFTypedLiteral tLit = (RDFTypedLiteral)triple.Object; XmlAttribute typedLiteralNodeDesc = rdfDoc.CreateAttribute(RDFVocabulary.RDF.PREFIX + ":datatype", RDFVocabulary.RDF.BASE_URI); XmlText typedLiteralNodeDescText = rdfDoc.CreateTextNode(RDFModelUtilities.GetDatatypeFromEnum(tLit.Datatype)); typedLiteralNodeDesc.AppendChild(typedLiteralNodeDescText); predNode.Attributes.Append(typedLiteralNodeDesc); } #endregion //litVALUE</predPREF:predURI>" XmlText litNodeDescText = rdfDoc.CreateTextNode(((RDFLiteral)triple.Object).Value); predNode.AppendChild(litNodeDescText); } #endregion subjNode.AppendChild(predNode); } } //Raw containers must not be written as-is, instead they have to be saved //and attached when their subj is found later as object of a triple if (!subjNode.Name.Equals(RDFVocabulary.RDF.PREFIX + ":Bag", StringComparison.Ordinal) && !subjNode.Name.Equals(RDFVocabulary.RDF.PREFIX + ":Seq", StringComparison.Ordinal) && !subjNode.Name.Equals(RDFVocabulary.RDF.PREFIX + ":Alt", StringComparison.Ordinal)) { rdfRoot.AppendChild(subjNode); } #endregion } #endregion rdfDoc.AppendChild(rdfRoot); #endregion rdfDoc.Save(rdfxmlWriter); } #endregion } catch (Exception ex) { throw new RDFModelException("Cannot serialize Xml because: " + ex.Message, ex); } }
/// <summary> /// Deserializes the given Xml stream to a graph. /// </summary> internal static RDFGraph Deserialize(Stream inputStream) { try { #region deserialize XmlReaderSettings xrs = new XmlReaderSettings(); xrs.IgnoreComments = true; xrs.DtdProcessing = DtdProcessing.Ignore; RDFGraph result = new RDFGraph(); using (XmlReader xr = XmlReader.Create(new StreamReader(inputStream, Encoding.UTF8), xrs)) { #region load XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(xr); #endregion #region root //Prepare the namespace table for the Xml selections var nsMgr = new XmlNamespaceManager(new NameTable()); nsMgr.AddNamespace(RDFVocabulary.RDF.PREFIX, RDFVocabulary.RDF.BASE_URI); //Select "rdf:RDF" root node XmlNode rdfRDF = GetRdfRootNode(xmlDoc, nsMgr); #endregion #region prefixes //Select "xmlns" attributes and try to add them to the namespace register var xmlnsAttrs = GetXmlnsNamespaces(rdfRDF, nsMgr); //Try to get the "xml:base" attribute, which is needed to resolve eventual relative #IDs in "rdf:about" nodes //If it is not found, set it to the graph Uri Uri xmlBase = null; if (xmlnsAttrs != null && xmlnsAttrs.Count > 0) { var xmlBaseAttr = (rdfRDF.Attributes["xml:base"] ?? rdfRDF.Attributes["xmlns"]); if (xmlBaseAttr != null) { xmlBase = RDFModelUtilities.GetUriFromString(xmlBaseAttr.Value); } } //Always keep in synch the Context and the xmlBase if (xmlBase != null) { result.SetContext(xmlBase); } else { xmlBase = result.Context; } #endregion #region elements //Parse resource elements, which are the childs of root node and represent the subjects if (rdfRDF.HasChildNodes) { var subjNodesEnum = rdfRDF.ChildNodes.GetEnumerator(); while (subjNodesEnum != null && subjNodesEnum.MoveNext()) { #region subj //Get the current resource node XmlNode subjNode = (XmlNode)subjNodesEnum.Current; RDFResource subj = GetSubjectNode(subjNode, xmlBase, result); if (subj == null) { continue; } #endregion #region predObjList //Parse pred elements, which are the childs of subj element if (subjNode.HasChildNodes) { IEnumerator predNodesEnum = subjNode.ChildNodes.GetEnumerator(); while (predNodesEnum != null && predNodesEnum.MoveNext()) { //Get the current pred node RDFResource pred = null; XmlNode predNode = (XmlNode)predNodesEnum.Current; if (predNode.NamespaceURI == String.Empty) { pred = new RDFResource(xmlBase + predNode.LocalName); } else { pred = (predNode.LocalName.StartsWith("autoNS") ? new RDFResource(predNode.NamespaceURI) : new RDFResource(predNode.NamespaceURI + predNode.LocalName)); } #region object //Check if there is a "rdf:about" or a "rdf:resource" attribute XmlAttribute rdfObject = (GetRdfAboutAttribute(predNode) ?? GetRdfResourceAttribute(predNode)); if (rdfObject != null) { //Attribute found, but we must check if it is "rdf:ID", "rdf:nodeID" or a relative Uri String rdfObjectValue = ResolveRelativeNode(rdfObject, xmlBase); RDFResource obj = new RDFResource(rdfObjectValue); result.AddTriple(new RDFTriple(subj, pred, obj)); continue; } #endregion #region typed literal //Check if there is a "rdf:datatype" attribute XmlAttribute rdfDatatype = GetRdfDatatypeAttribute(predNode); if (rdfDatatype != null) { RDFModelEnums.RDFDatatype dt = RDFModelUtilities.GetDatatypeFromString(rdfDatatype.Value); RDFTypedLiteral tLit = new RDFTypedLiteral(HttpUtility.HtmlDecode(predNode.InnerText), dt); result.AddTriple(new RDFTriple(subj, pred, tLit)); continue; } //Check if there is a "rdf:parseType=Literal" attribute XmlAttribute parseLiteral = GetParseTypeLiteralAttribute(predNode); if (parseLiteral != null) { RDFTypedLiteral tLit = new RDFTypedLiteral(HttpUtility.HtmlDecode(predNode.InnerXml), RDFModelEnums.RDFDatatype.RDFS_LITERAL); result.AddTriple(new RDFTriple(subj, pred, tLit)); continue; } #endregion #region plain literal //Check if there is a "xml:lang" attribute, or if a unique textual child XmlAttribute xmlLang = GetXmlLangAttribute(predNode); if (xmlLang != null || (predNode.HasChildNodes && predNode.ChildNodes.Count == 1 && predNode.ChildNodes[0].NodeType == XmlNodeType.Text)) { RDFPlainLiteral pLit = new RDFPlainLiteral(HttpUtility.HtmlDecode(predNode.InnerText), (xmlLang != null ? xmlLang.Value : String.Empty)); result.AddTriple(new RDFTriple(subj, pred, pLit)); continue; } #endregion #region collection //Check if there is a "rdf:parseType=Collection" attribute XmlAttribute rdfCollect = GetParseTypeCollectionAttribute(predNode); if (rdfCollect != null) { ParseCollectionElements(xmlBase, predNode, subj, pred, result); continue; } #endregion #region container //Check if there is a "rdf:[Bag|Seq|Alt]" child node XmlNode container = GetContainerNode(predNode); if (container != null) { //Distinguish the right type of RDF container to build if (container.LocalName.Equals(RDFVocabulary.RDF.PREFIX + ":Bag", StringComparison.Ordinal) || container.LocalName.Equals("Bag", StringComparison.Ordinal)) { ParseContainerElements(RDFModelEnums.RDFContainerType.Bag, container, subj, pred, result); } else if (container.LocalName.Equals(RDFVocabulary.RDF.PREFIX + ":Seq", StringComparison.Ordinal) || container.LocalName.Equals("Seq", StringComparison.Ordinal)) { ParseContainerElements(RDFModelEnums.RDFContainerType.Seq, container, subj, pred, result); } else if (container.LocalName.Equals(RDFVocabulary.RDF.PREFIX + ":Alt", StringComparison.Ordinal) || container.LocalName.Equals("Alt", StringComparison.Ordinal)) { ParseContainerElements(RDFModelEnums.RDFContainerType.Alt, container, subj, pred, result); } } #endregion } } #endregion } } #endregion } return(result); #endregion } catch (Exception ex) { throw new RDFModelException("Cannot deserialize Xml because: " + ex.Message, ex); } }
/// <summary> /// Deserializes the given Xml filepath to a graph. /// </summary> internal static RDFGraph Deserialize(String filepath) { try { #region deserialize XmlReaderSettings xrs = new XmlReaderSettings(); xrs.IgnoreComments = true; xrs.DtdProcessing = DtdProcessing.Ignore; RDFGraph result = new RDFGraph(); using(XmlReader xr = XmlReader.Create(new StreamReader(filepath, Encoding.UTF8), xrs)) { #region load XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(xr); #endregion #region root //Prepare the namespace table for the Xml selections var nsMgr = new XmlNamespaceManager(new NameTable()); nsMgr.AddNamespace(RDFVocabulary.RDF.PREFIX, RDFVocabulary.RDF.BASE_URI); //Select "rdf:RDF" root node XmlNode rdfRDF = RDFModelUtilities.GetRdfRootNode(xmlDoc, nsMgr); #endregion #region prefixes //Select "xmlns" attributes and try to add them to the namespace register var xmlnsAttrs = RDFModelUtilities.GetXmlnsNamespaces(rdfRDF, nsMgr); //Try to get the "xml:base" attribute, which is needed to resolve eventual relative #IDs in "rdf:about" nodes //If it is not found, set it to the graph Uri Uri xmlBase = null; if (xmlnsAttrs != null && xmlnsAttrs.Count > 0) { var xmlBaseAttr = (rdfRDF.Attributes["xml:base"] ?? rdfRDF.Attributes["xmlns"]); if (xmlBaseAttr != null) { xmlBase = RDFModelUtilities.GetUriFromString(xmlBaseAttr.Value); } } //Always keep in synch the Context and the xmlBase if (xmlBase != null) { result.SetContext(xmlBase); } else { xmlBase = result.Context; } #endregion #region elements //Parse resource elements, which are the childs of root node and represent the subjects if (rdfRDF.HasChildNodes) { var subjNodesEnum = rdfRDF.ChildNodes.GetEnumerator(); while (subjNodesEnum != null && subjNodesEnum.MoveNext()) { #region subj //Get the current resource node XmlNode subjNode = (XmlNode)subjNodesEnum.Current; RDFResource subj = RDFModelUtilities.GetSubjectNode(subjNode, xmlBase, result); if (subj == null) { continue; } #endregion #region predObjList //Parse pred elements, which are the childs of subj element if (subjNode.HasChildNodes) { IEnumerator predNodesEnum = subjNode.ChildNodes.GetEnumerator(); while (predNodesEnum != null && predNodesEnum.MoveNext()) { //Get the current pred node RDFResource pred = null; XmlNode predNode = (XmlNode)predNodesEnum.Current; if (predNode.NamespaceURI == String.Empty) { pred = new RDFResource(xmlBase + predNode.LocalName); } else { pred = (predNode.LocalName.StartsWith("autoNS") ? new RDFResource(predNode.NamespaceURI) : new RDFResource(predNode.NamespaceURI + predNode.LocalName)); } #region object //Check if there is a "rdf:about" or a "rdf:resource" attribute XmlAttribute rdfObject = (RDFModelUtilities.GetRdfAboutAttribute(predNode) ?? RDFModelUtilities.GetRdfResourceAttribute(predNode)); if (rdfObject != null) { //Attribute found, but we must check if it is "rdf:ID", "rdf:nodeID" or a relative Uri String rdfObjectValue = RDFModelUtilities.ResolveRelativeNode(rdfObject, xmlBase); RDFResource obj = new RDFResource(rdfObjectValue); result.AddTriple(new RDFTriple(subj, pred, obj)); continue; } #endregion #region typed literal //Check if there is a "rdf:datatype" attribute XmlAttribute rdfDatatype = RDFModelUtilities.GetRdfDatatypeAttribute(predNode); if (rdfDatatype != null) { RDFDatatype dt = RDFModelUtilities.GetDatatypeFromString(rdfDatatype.Value); RDFTypedLiteral tLit = new RDFTypedLiteral(HttpUtility.HtmlDecode(predNode.InnerText), dt); result.AddTriple(new RDFTriple(subj, pred, tLit)); continue; } //Check if there is a "rdf:parseType=Literal" attribute XmlAttribute parseLiteral = RDFModelUtilities.GetParseTypeLiteralAttribute(predNode); if (parseLiteral != null) { RDFTypedLiteral tLit = new RDFTypedLiteral(HttpUtility.HtmlDecode(predNode.InnerXml), RDFDatatypeRegister.GetByPrefixAndDatatype(RDFVocabulary.RDFS.PREFIX, "Literal")); result.AddTriple(new RDFTriple(subj, pred, tLit)); continue; } #endregion #region plain literal //Check if there is a "xml:lang" attribute, or if a unique textual child XmlAttribute xmlLang = RDFModelUtilities.GetXmlLangAttribute(predNode); if (xmlLang != null || (predNode.HasChildNodes && predNode.ChildNodes.Count == 1 && predNode.ChildNodes[0].NodeType == XmlNodeType.Text)) { RDFPlainLiteral pLit = new RDFPlainLiteral(HttpUtility.HtmlDecode(predNode.InnerText), (xmlLang != null ? xmlLang.Value : String.Empty)); result.AddTriple(new RDFTriple(subj, pred, pLit)); continue; } #endregion #region collection //Check if there is a "rdf:parseType=Collection" attribute XmlAttribute rdfCollect = RDFModelUtilities.GetParseTypeCollectionAttribute(predNode); if (rdfCollect != null) { RDFModelUtilities.ParseCollectionElements(xmlBase, predNode, subj, pred, result); continue; } #endregion #region container //Check if there is a "rdf:[Bag|Seq|Alt]" child node XmlNode container = RDFModelUtilities.GetContainerNode(predNode); if (container != null) { //Distinguish the right type of RDF container to build if (container.LocalName.Equals(RDFVocabulary.RDF.PREFIX + ":Bag", StringComparison.Ordinal) || container.LocalName.Equals("Bag", StringComparison.Ordinal)) { RDFModelUtilities.ParseContainerElements(RDFModelEnums.RDFContainerTypes.Bag, container, subj, pred, result); } else if (container.LocalName.Equals(RDFVocabulary.RDF.PREFIX + ":Seq", StringComparison.Ordinal) || container.LocalName.Equals("Seq", StringComparison.Ordinal)) { RDFModelUtilities.ParseContainerElements(RDFModelEnums.RDFContainerTypes.Seq, container, subj, pred, result); } else if (container.LocalName.Equals(RDFVocabulary.RDF.PREFIX + ":Alt", StringComparison.Ordinal) || container.LocalName.Equals("Alt", StringComparison.Ordinal)) { RDFModelUtilities.ParseContainerElements(RDFModelEnums.RDFContainerTypes.Alt, container, subj, pred, result); } } #endregion } } #endregion } } #endregion } return result; #endregion } catch (Exception ex) { throw new RDFModelException("Cannot deserialize Xml because: " + ex.Message, ex); } }
/// <summary> /// Deserializes the given N-Triples stream to a graph. /// </summary> internal static RDFGraph Deserialize(Stream inputStream) { Int64 ntripleIndex = 0; try { #region deserialize using (StreamReader sr = new StreamReader(inputStream, Encoding.ASCII)) { RDFGraph result = new RDFGraph(); String ntriple = String.Empty; String[] tokens = new String[3]; RDFResource S = null; RDFResource P = null; RDFResource O = null; RDFLiteral L = null; while((ntriple = sr.ReadLine()) != null) { ntripleIndex++; #region sanitize & tokenize //Cleanup previous data S = null; tokens[0] = String.Empty; P = null; tokens[1] = String.Empty; O = null; L = null; tokens[2] = String.Empty; //Preliminary sanitizations: clean trailing space-like chars ntriple = ntriple.Trim(new Char[] { ' ', '\t', '\r', '\n' }); //Skip empty or comment lines if (ntriple == String.Empty || ntriple.StartsWith("#")) { continue; } //Tokenizes the sanitized triple tokens = TokenizeNTriple(ntriple); #endregion #region subj String subj = tokens[0].TrimStart(new Char[] { '<' }) .TrimEnd(new Char[] { '>' }) .Replace("_:", "bnode:"); S = new RDFResource(RDFModelUtilities.ASCII_To_Unicode(subj)); #endregion #region pred String pred = tokens[1].TrimStart(new Char[] { '<' }) .TrimEnd(new Char[] { '>' }); P = new RDFResource(RDFModelUtilities.ASCII_To_Unicode(pred)); #endregion #region object if (tokens[2].StartsWith("<") || tokens[2].StartsWith("bnode:") || tokens[2].StartsWith("_:")) { String obj = tokens[2].TrimStart(new Char[] { '<' }) .TrimEnd(new Char[] { '>' }) .Replace("_:", "bnode:") .Trim(new Char[] { ' ', '\n', '\t', '\r' }); O = new RDFResource(RDFModelUtilities.ASCII_To_Unicode(obj)); } #endregion #region literal else { #region sanitize tokens[2] = regexSqt.Replace(tokens[2], String.Empty); tokens[2] = regexEqt.Replace(tokens[2], String.Empty); tokens[2] = tokens[2].Replace("\\\\", "\\") .Replace("\\\"", "\"") .Replace("\\n", "\n") .Replace("\\t", "\t") .Replace("\\r", "\r"); tokens[2] = RDFModelUtilities.ASCII_To_Unicode(tokens[2]); #endregion #region plain literal if (!tokens[2].Contains("^^") || tokens[2].EndsWith("^^") || tokens[2].Substring(tokens[2].LastIndexOf("^^", StringComparison.Ordinal) + 2, 1) != "<") { if (regexLPL.Match(tokens[2]).Success) { tokens[2] = tokens[2].Replace("\"@", "@"); String pLitValue = tokens[2].Substring(0, tokens[2].LastIndexOf("@", StringComparison.Ordinal)); String pLitLang = tokens[2].Substring(tokens[2].LastIndexOf("@", StringComparison.Ordinal) + 1); L = new RDFPlainLiteral(HttpUtility.HtmlDecode(pLitValue), pLitLang); } else { L = new RDFPlainLiteral(HttpUtility.HtmlDecode(tokens[2])); } } #endregion #region typed literal else { tokens[2] = tokens[2].Replace("\"^^", "^^"); String tLitValue = tokens[2].Substring(0, tokens[2].LastIndexOf("^^", StringComparison.Ordinal)); String tLitDatatype = tokens[2].Substring(tokens[2].LastIndexOf("^^", StringComparison.Ordinal) + 2) .TrimStart(new Char[] { '<' }) .TrimEnd(new Char[] { '>' }); RDFModelEnums.RDFDatatypes dt = RDFModelUtilities.GetDatatypeFromString(tLitDatatype); L = new RDFTypedLiteral(HttpUtility.HtmlDecode(tLitValue), dt); } #endregion } #endregion #region addtriple if (O != null) { result.AddTriple(new RDFTriple(S, P, O)); } else { result.AddTriple(new RDFTriple(S, P, L)); } #endregion } return result; } #endregion } catch(Exception ex) { throw new RDFModelException("Cannot deserialize N-Triples (line " + ntripleIndex + ") because: " + ex.Message, ex); } }
/// <summary> /// Deserializes the given N-Quads stream to a memory store. /// </summary> internal static RDFMemoryStore Deserialize(Stream inputStream) { Int64 nquadIndex = 0; try { #region deserialize using (StreamReader sr = new StreamReader(inputStream, Encoding.ASCII)) { RDFMemoryStore result = new RDFMemoryStore(); String nquad = String.Empty; String[] tokens = new String[4]; RDFResource S = null; RDFResource P = null; RDFResource O = null; RDFLiteral L = null; RDFContext C = new RDFContext(); while((nquad = sr.ReadLine()) != null) { nquadIndex++; #region sanitize & tokenize //Cleanup previous data S = null; tokens[0] = String.Empty; P = null; tokens[1] = String.Empty; O = null; L = null; tokens[2] = String.Empty; C = new RDFContext(); tokens[3] = String.Empty; //Preliminary sanitizations: clean trailing space-like chars nquad = nquad.Trim(new Char[] { ' ', '\t', '\r', '\n' }); //Skip empty or comment lines if (nquad == String.Empty || nquad.StartsWith("#")) { continue; } //Tokenizes the sanitized quad tokens = TokenizeNQuad(nquad); #endregion #region subj String subj = tokens[0].TrimStart(new Char[] { '<' }) .TrimEnd(new Char[] { '>' }) .Replace("_:", "bnode:"); S = new RDFResource(RDFModelUtilities.ASCII_To_Unicode(subj)); #endregion #region pred String pred = tokens[1].TrimStart(new Char[] { '<' }) .TrimEnd(new Char[] { '>' }); P = new RDFResource(RDFModelUtilities.ASCII_To_Unicode(pred)); #endregion #region object if (tokens[2].StartsWith("<") || tokens[2].StartsWith("bnode:") || tokens[2].StartsWith("_:")) { String obj = tokens[2].TrimStart(new Char[] { '<' }) .TrimEnd(new Char[] { '>' }) .Replace("_:", "bnode:") .Trim(new Char[] { ' ', '\n', '\t', '\r' }); O = new RDFResource(RDFModelUtilities.ASCII_To_Unicode(obj)); } #endregion #region literal else { #region sanitize tokens[2] = RDFNTriples.regexSqt.Replace(tokens[2], String.Empty); tokens[2] = RDFNTriples.regexEqt.Replace(tokens[2], String.Empty); tokens[2] = tokens[2].Replace("\\\\", "\\") .Replace("\\\"", "\"") .Replace("\\n", "\n") .Replace("\\t", "\t") .Replace("\\r", "\r"); tokens[2] = RDFModelUtilities.ASCII_To_Unicode(tokens[2]); #endregion #region plain literal if (!tokens[2].Contains("^^") || tokens[2].EndsWith("^^") || tokens[2].Substring(tokens[2].LastIndexOf("^^", StringComparison.Ordinal) + 2, 1) != "<") { if (RDFNTriples.regexLPL.Match(tokens[2]).Success) { tokens[2] = tokens[2].Replace("\"@", "@"); String pLitValue = tokens[2].Substring(0, tokens[2].LastIndexOf("@", StringComparison.Ordinal)); String pLitLang = tokens[2].Substring(tokens[2].LastIndexOf("@", StringComparison.Ordinal) + 1); L = new RDFPlainLiteral(HttpUtility.HtmlDecode(pLitValue), pLitLang); } else { L = new RDFPlainLiteral(HttpUtility.HtmlDecode(tokens[2])); } } #endregion #region typed literal else { tokens[2] = tokens[2].Replace("\"^^", "^^"); String tLitValue = tokens[2].Substring(0, tokens[2].LastIndexOf("^^", StringComparison.Ordinal)); String tLitDatatype = tokens[2].Substring(tokens[2].LastIndexOf("^^", StringComparison.Ordinal) + 2) .TrimStart(new Char[] { '<' }) .TrimEnd(new Char[] { '>' }); RDFModelEnums.RDFDatatypes dt = RDFModelUtilities.GetDatatypeFromString(tLitDatatype); L = new RDFTypedLiteral(HttpUtility.HtmlDecode(tLitValue), dt); } #endregion } #endregion #region context if (!String.IsNullOrEmpty(tokens[3])) { String ctx = tokens[3].TrimStart(new Char[] { '<' }) .TrimEnd(new Char[] { '>' }); Uri ctxUri = null; if (Uri.TryCreate(ctx, UriKind.Absolute, out ctxUri)) { C = new RDFContext(RDFModelUtilities.ASCII_To_Unicode(ctxUri.ToString())); } else { throw new RDFModelException("found context '" + ctx +"' which is not a well-formed absolute Uri"); } } #endregion #region addquadruple if (O != null) { result.AddQuadruple(new RDFQuadruple(C, S, P, O)); } else { result.AddQuadruple(new RDFQuadruple(C, S, P, L)); } #endregion } return result; } #endregion } catch(Exception ex) { throw new RDFModelException("Cannot deserialize N-Quads (line " + nquadIndex + ") because: " + ex.Message, ex); } }