### Install rdfxml-streaming-parser with Yarn
Source: https://github.com/rdfjs/rdfxml-streaming-parser.js/blob/master/README.md
Installs the rdfxml-streaming-parser package using Yarn. This command is typically run in a Node.js project's root directory.
```bash
yarn install rdfxml-streaming-parser
```
--------------------------------
### Configure rdfxml-streaming-parser.js with Advanced Options
Source: https://context7.com/rdfjs/rdfxml-streaming-parser.js/llms.txt
Configure the parser with custom data factory, validation settings, and error handling. This example shows how to set a custom data factory, base IRI, default graph, and various parsing flags like strict mode and IRI validation.
```javascript
const { RdfXmlParser } = require('rdfxml-streaming-parser');
const { DataFactory } = require('rdf-data-factory');
const { IriValidationStrategy } = require('validate-iri');
const customDataFactory = new DataFactory();
const defaultGraph = customDataFactory.namedNode('http://example.org/graph1');
const parser = new RdfXmlParser({
dataFactory: customDataFactory,
baseIRI: 'http://example.org/documents/doc1',
defaultGraph: defaultGraph,
strict: true,
trackPosition: true,
allowDuplicateRdfIds: false,
validateUri: true,
iriValidationStrategy: IriValidationStrategy.Strict,
parseUnsupportedVersions: false
});
const rdfXml = `
The Great BookJohn Doe2023-01-15`;
parser.write(rdfXml);
parser.end();
parser.on('data', (quad) => {
console.log(`Graph: ${quad.graph.value}`);
console.log(`Subject: ${quad.subject.value}`);
console.log(`Predicate: ${quad.predicate.value}`);
console.log(`Object: ${quad.object.value}`);
});
```
--------------------------------
### Parse Blank Nodes and Collections with rdfxml-streaming-parser.js
Source: https://context7.com/rdfjs/rdfxml-streaming-parser.js/llms.txt
Handle RDF collections (lists) and blank nodes in RDF/XML documents. This example parses an RDF/XML string containing a blank node with properties, an RDF collection, and a named blank node, logging details about the parsed quads.
```javascript
const { RdfXmlParser } = require('rdfxml-streaming-parser');
const parser = new RdfXmlParser({
baseIRI: 'http://example.org/',
allowDuplicateRdfIds: false
});
const rdfWithCollections = `
123 Main StNew YorkValue`;
const quads = [];
parser.on('data', (quad) => {
quads.push(quad);
if (quad.subject.termType === 'BlankNode') {
console.log(`Blank node: _:${quad.subject.value}`);
}
});
parser.on('end', () => {
console.log(`Total quads parsed: ${quads.length}`);
// Collections are expanded into rdf:first and rdf:rest triples
const listTriples = quads.filter(q =>
q.predicate.value.includes('first') || q.predicate.value.includes('rest')
);
console.log(`List structure triples: ${listTriples.length}`);
});
parser.write(rdfWithCollections);
parser.end();
```
--------------------------------
### RdfXmlParser Error Handling with Position Tracking
Source: https://context7.com/rdfjs/rdfxml-streaming-parser.js/llms.txt
This example demonstrates how to enable position tracking in RdfXmlParser for detailed error reporting, including line and column numbers. It configures the parser with `trackPosition: true`, `strict: true`, and `validateUri: true` and processes invalid RDF data, logging errors to the console.
```javascript
const { RdfXmlParser } = require('rdfxml-streaming-parser');
const parserWithTracking = new RdfXmlParser({
trackPosition: true,
strict: true,
validateUri: true
});
const invalidRdf = `
Value 1Value 2`;
parserWithTracking.on('data', (quad) => {
console.log('Quad parsed:', quad);
});
parserWithTracking.on('error', (error) => {
// Error message includes line and column when trackPosition is true
console.error('Parse error with position:', error.message);
// Output example: "Line 5 column 30: Found multiple occurrences of rdf:ID='duplicate'."
});
parserWithTracking.write(invalidRdf);
parserWithTracking.end();
```
--------------------------------
### Write RDF/XML Strings to Parser for In-Memory Processing
Source: https://context7.com/rdfjs/rdfxml-streaming-parser.js/llms.txt
This example shows how to manually write RDF/XML content as strings to the RdfXmlParser for in-memory processing. It configures a base IRI and listens for 'data', 'error', and 'end' events to process the resulting quads. This is useful for smaller, dynamically generated RDF/XML data.
```javascript
const { RdfXmlParser } = require('rdfxml-streaming-parser');
const parser = new RdfXmlParser({ baseIRI: 'http://example.org/' });
parser
.on('data', (quad) => {
console.log(`Triple: <${quad.subject.value}> <${quad.predicate.value}> <${quad.object.value}>`);
})
.on('error', (error) => {
console.error('Error:', error.message);
})
.on('end', () => {
console.log('Done parsing');
});
parser.write('');
parser.write('');
parser.write(' ');
parser.write(' Example Resource');
parser.write(' 42');
parser.write(' ');
parser.write('');
parser.end();
```
--------------------------------
### RdfXmlParser Constructor Configuration
Source: https://github.com/rdfjs/rdfxml-streaming-parser.js/blob/master/README.md
This section describes the optional parameters that can be set when initializing the RdfXmlParser. These options allow for fine-grained control over how RDF/XML data is parsed.
```APIDOC
## RdfXmlParser Constructor
Optionally, the following parameters can be set in the `RdfXmlParser` constructor:
* `dataFactory`: A custom [RDFJS DataFactory](http://rdf.js.org/#datafactory-interface) to construct terms and triples. _(Default: `require('@rdfjs/data-model')`)_
* `baseIRI`: An initial default base IRI. _(Default: `''`)
* `defaultGraph`: The default graph for constructing [quads](http://rdf.js.org/#dom-datafactory-quad). _(Default: `defaultGraph()`)_
* `strict`: If the internal SAX parser should parse XML in strict mode, and error if it is invalid. _(Default: `false`)
* `trackPosition`: If the internal position (line, column) should be tracked an emitted in error messages. _(Default: `false`)
* `allowDuplicateRdfIds`: By default [multiple occurrences of the same `rdf:ID` value are not allowed](https://www.w3.org/TR/rdf-syntax-grammar/#section-Syntax-ID-xml-base). By setting this option to `true`, this uniqueness check can be disabled. _(Default: `false`)
* `validateUri`: By default, the parser validates each URI. _(Default: `true`)
* `iriValidationStrategy`: Allows to customize the used IRI validation strategy using the `IriValidationStrategy` enumeration. IRI validation is handled by [validate-iri.js](https://github.com/comunica/validate-iri.js/). _(Default: `IriValidationStrategy.Pragmatic`)_
* `parseUnsupportedVersions`: If no error should be emitted on unsupported versions. _(Default: `false`)
* `version`: The version that was supplied as a media type parameter. _(Default: `undefined`)
### Request Example
```javascript
new RdfXmlParser({
dataFactory: require('@rdfjs/data-model'),
baseIRI: 'http://example.org/',
defaultGraph: namedNode('http://example.org/graph'),
strict: true,
trackPosition: true,
allowDuplicateRdfIds: true,
validateUri: true,
parseUnsupportedVersions: false,
});
```
```
--------------------------------
### Instantiate RdfXmlParser with Custom Configuration (JavaScript)
Source: https://github.com/rdfjs/rdfxml-streaming-parser.js/blob/master/README.md
Demonstrates how to instantiate the RdfXmlParser with a custom configuration object. This allows for setting various parsing options like dataFactory, baseIRI, defaultGraph, strict mode, position tracking, duplicate RDF ID handling, URI validation, and parsing of unsupported versions. The default values for each option are also provided in the documentation.
```javascript
new RdfXmlParser({
dataFactory: require('@rdfjs/data-model'),
baseIRI: 'http://example.org/',
defaultGraph: namedNode('http://example.org/graph'),
strict: true,
trackPosition: true,
allowDuplicateRdfIds: true,
validateUri: true,
parseUnsupportedVersions: false
});
```
--------------------------------
### Import RdfXmlParser using CommonJS
Source: https://github.com/rdfjs/rdfxml-streaming-parser.js/blob/master/README.md
Demonstrates how to import the RdfXmlParser class from the 'rdfxml-streaming-parser' package using CommonJS syntax.
```javascript
const RdfXmlParser = require("rdfxml-streaming-parser").RdfXmlParser;
```
--------------------------------
### Import RdfXmlParser using ES Modules
Source: https://github.com/rdfjs/rdfxml-streaming-parser.js/blob/master/README.md
Demonstrates how to import the RdfXmlParser class from the 'rdfxml-streaming-parser' package using ES Module syntax.
```javascript
import {RdfXmlParser} from "rdfxml-streaming-parser";
```
--------------------------------
### Parse Stream using RDFJS Sink Interface with Import Method
Source: https://context7.com/rdfjs/rdfxml-streaming-parser.js/llms.txt
This snippet demonstrates using the RDFJS Sink interface's 'import' method to parse an RDF/XML stream from a file. It shows how to configure the parser with a base IRI and track source positions, and processes literal quad objects to log their values, language, and datatype. It also includes error handling and completion logging.
```javascript
const { RdfXmlParser } = require('rdfxml-streaming-parser');
const fs = require('fs');
const parser = new RdfXmlParser({
baseIRI: 'http://example.org/base/',
trackPosition: true
});
const textStream = fs.createReadStream('mydata.rdf');
parser.import(textStream)
.on('data', (quad) => {
if (quad.object.termType === 'Literal') {
console.log(`Literal value: ${quad.object.value}`);
if (quad.object.language) {
console.log(`Language: ${quad.object.language}`);
}
if (quad.object.datatype) {
console.log(`Datatype: ${quad.object.datatype.value}`);
}
}
})
.on('error', (error) => {
console.error('Parsing error:', error.message);
})
.on('end', () => {
console.log('Stream parsing finished');
});
```
--------------------------------
### Import RDF/XML Stream using Sink Interface
Source: https://github.com/rdfjs/rdfxml-streaming-parser.js/blob/master/README.md
Parses an RDF/XML stream from 'myfile.rdf' using the RdfXmlParser's `import` method, which adheres to the RDFJS Sink interface. Logs quads, errors, and completion.
```javascript
const {RdfXmlParser} = require("rdfxml-streaming-parser");
const fs = require('fs');
const myParser = new RdfXmlParser();
const myTextStream = fs.createReadStream('myfile.rdf');
myParser.import(myTextStream)
.on('data', console.log)
.on('error', console.error)
.on('end', () => console.log('All triples were parsed!'));
```
--------------------------------
### Manually Write RDF/XML Strings to Parser
Source: https://github.com/rdfjs/rdfxml-streaming-parser.js/blob/master/README.md
Demonstrates writing RDF/XML data chunk by chunk directly to an RdfXmlParser instance. The parser processes these strings and outputs quads.
```javascript
const {RdfXmlParser} = require("rdfxml-streaming-parser");
const myParser = new RdfXmlParser();
myParser
.on('data', console.log)
.on('error', console.error)
.on('end', () => console.log('All triples were parsed!'));
myParser.write('');
myParser.write(``);
myParser.write(``);
myParser.write(``);
myParser.write(``);
myParser.write(``);
myParser.end();
```
--------------------------------
### Parse RDF/XML from File Stream to RDFJS Quads
Source: https://context7.com/rdfjs/rdfxml-streaming-parser.js/llms.txt
This snippet demonstrates how to parse an RDF/XML file stream using the RdfXmlParser and outputting each quad to the console. It utilizes Node.js streams for efficient processing and includes basic error handling. Dependencies include 'rdfxml-streaming-parser' and 'fs'.
```javascript
const { RdfXmlParser } = require('rdfxml-streaming-parser');
const fs = require('fs');
const parser = new RdfXmlParser();
fs.createReadStream('data.rdf')
.pipe(parser)
.on('data', (quad) => {
console.log(`Subject: ${quad.subject.value}`);
console.log(`Predicate: ${quad.predicate.value}`);
console.log(`Object: ${quad.object.value}`);
console.log(`Graph: ${quad.graph.value}`);
})
.on('error', (error) => {
console.error('Parse error:', error.message);
})
.on('end', () => {
console.log('Parsing complete!');
});
```
--------------------------------
### Configure IRI Validation Strategies
Source: https://context7.com/rdfjs/rdfxml-streaming-parser.js/llms.txt
This snippet shows how to configure the IRI validation behavior of `RdfXmlParser` using different strategies provided by the `validate-iri` library. It initializes parsers with strict, pragmatic (default), and no validation options, then processes an RDF/XML string with URIs, logging valid quads or errors.
```javascript
const { RdfXmlParser } = require('rdfxml-streaming-parser');
const { IriValidationStrategy } = require('validate-iri');
// Strict validation - rejects more URIs
const strictParser = new RdfXmlParser({
validateUri: true,
iriValidationStrategy: IriValidationStrategy.Strict
});
// Pragmatic validation (default) - balanced approach
const pragmaticParser = new RdfXmlParser({
validateUri: true,
iriValidationStrategy: IriValidationStrategy.Pragmatic
});
// No validation - accepts all URIs
const noValidationParser = new RdfXmlParser({
validateUri: false,
iriValidationStrategy: IriValidationStrategy.None
});
const rdfWithUris = `
`;
pragmaticParser.on('data', (quad) => {
console.log('Valid quad:', quad);
});
pragmaticParser.on('error', (error) => {
console.error('IRI validation error:', error.message);
});
pragmaticParser.write(rdfWithUris);
pragmaticParser.end();
```
--------------------------------
### Handle RDF Version Attributes with rdfxml-streaming-parser.js
Source: https://context7.com/rdfjs/rdfxml-streaming-parser.js/llms.txt
Listen to version events and control parsing of unsupported RDF versions. This demonstrates two parsers: one strict that logs detected versions and errors, and one lenient that proceeds with parsing even if the version is unsupported.
```javascript
const { RdfXmlParser } = require('rdfxml-streaming-parser');
// Parser that emits version events
const strictParser = new RdfXmlParser({
parseUnsupportedVersions: false
});
strictParser.on('version', (version) => {
console.log(`Detected RDF version: ${version}`);
// Supported versions: 1.1, 1.2, 1.2-basic
});
strictParser.on('error', (error) => {
console.error('Version error:', error.message);
});
// Parser that allows unsupported versions
const lenientParser = new RdfXmlParser({
parseUnsupportedVersions: true
});
lenientParser.on('version', (version) => {
console.log(`Parsing version: ${version} (even if unsupported)`);
});
const rdfWithVersion = `
`;
lenientParser.write(rdfWithVersion);
lenientParser.end();
```
--------------------------------
### Parse RDF/XML and Log Version Attributes
Source: https://github.com/rdfjs/rdfxml-streaming-parser.js/blob/master/README.md
Parses an RDF/XML file, logs quads to the console, and specifically logs any 'rdf:version' attribute values encountered. Includes error handling and end-of-stream notification.
```javascript
const {RdfXmlParser} = require("rdfxml-streaming-parser");
const fs = require('fs');
const myParser = new RdfXmlParser();
fs.createReadStream('myfile.rdf')
.pipe(myParser)
.on('data', console.log)
.on('version', console.log) // Log rdf:version attribute values
.on('error', console.error)
.on('end', () => console.log('All triples were parsed!'));
```
--------------------------------
### Parse Nested Resources with parseType="Resource"
Source: https://context7.com/rdfjs/rdfxml-streaming-parser.js/llms.txt
This snippet demonstrates how to parse nested resource descriptions in RDF/XML using the `parseType="Resource"` attribute. It utilizes the `RdfXmlParser` to process an RDF/XML string and logs the resulting quads, highlighting the creation of blank nodes for nested properties.
```javascript
const { RdfXmlParser } = require('rdfxml-streaming-parser');
const parser = new RdfXmlParser({ baseIRI: 'http://example.org/' });
const rdfWithResource = `
John Smith456 Elm StreetBoston02101`;
const quads = [];
parser.on('data', (quad) => {
quads.push(quad);
console.log(`<${quad.subject.value}> <${quad.predicate.value}> <${quad.object.value}>`);
});
parser.on('end', () => {
console.log(`\nTotal quads: ${quads.length}`);
// parseType="Resource" creates a blank node for the nested properties
const blankNodes = quads.filter(q => q.subject.termType === 'BlankNode' || q.object.termType === 'BlankNode');
console.log(`Quads with blank nodes: ${blankNodes.length}`);
});
parser.write(rdfWithResource);
parser.end();
```
--------------------------------
### Parse RDF/XML from File Stream
Source: https://github.com/rdfjs/rdfxml-streaming-parser.js/blob/master/README.md
Parses an RDF/XML file ('myfile.rdf') using RdfXmlParser and streams the resulting quads to the console. Handles data, errors, and the end of the stream.
```javascript
const {RdfXmlParser} = require("rdfxml-streaming-parser");
const fs = require('fs');
const myParser = new RdfXmlParser();
fs.createReadStream('myfile.rdf')
.pipe(myParser)
.on('data', console.log)
.on('error', console.error)
.on('end', () => console.log('All triples were parsed!'));
```
--------------------------------
### Parse Typed Literals and Language Tags with RdfXmlParser
Source: https://context7.com/rdfjs/rdfxml-streaming-parser.js/llms.txt
This snippet shows how to use the RdfXmlParser to parse RDF/XML data containing typed literals (integers, decimals, booleans, dates) and language-tagged strings. It configures a parser with a base IRI and processes the parsed quads, logging details about literal values, languages, and datatypes.
```javascript
const { RdfXmlParser } = require('rdfxml-streaming-parser');
const parser = new RdfXmlParser({ baseIRI: 'http://example.org/' });
const rdfWithLiterals = `
Product NameNom du Produit29.99100true2023-06-15A plain string without type or language`;
parser.on('data', (quad) => {
if (quad.object.termType === 'Literal') {
console.log(`\nPredicate: ${quad.predicate.value}`);
console.log(`Value: ${quad.object.value}`);
if (quad.object.language) {
console.log(`Language: ${quad.object.language}`);
}
if (quad.object.datatype) {
console.log(`Datatype: ${quad.object.datatype.value}`);
}
}
});
parser.write(rdfWithLiterals);
parser.end();
```
--------------------------------
### Parse XML Literals with rdf:parseType="Literal"
Source: https://context7.com/rdfjs/rdfxml-streaming-parser.js/llms.txt
This snippet illustrates how to parse embedded XML content as RDF XMLLiterals using the RdfXmlParser. It configures a parser and processes RDF/XML data where a property value is defined with `rdf:parseType="Literal"`, containing XHTML content.
```javascript
const { RdfXmlParser } = require('rdfxml-streaming-parser');
const parser = new RdfXmlParser({ baseIRI: 'http://example.org/' });
const rdfWithXmlLiteral = `
Embedded HTML
This is embedded HTML content.
`;
parser.on('data', (quad) => {
if (quad.object.termType === 'Literal') {
console.log(`Value: ${quad.object.value}`);
console.log(`Datatype: ${quad.object.datatype.value}`);
// Datatype will be http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral
// Value contains the serialized XML content
}
});
parser.write(rdfWithXmlLiteral);
parser.end();
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.