Yasushi Shoji
Yasushi Shoji

Reputation: 4284

AsciiDoctor: How can I add custom xmlns'

How can I add a custom xmlns in the output when I convert an asciidoc file with AsciiDoctor?

I'd like to add xmlns:xi="http://www.w3.org/2001/XInclude" in the top book tag.

The current implementation seems to generate:

<?xml version="1.0" encoding="UTF-8"?>
<?asciidoc-toc?>
<?asciidoc-numbered?>
<book xmlns="http://docbook.org/ns/docbook" xmlns:xl="http://www.w3.org/1999/xlink" version="5.0" xml:lang="en">
<info>
<title>title</title>
</info>
</book>

from this:

= title
:lang: en

When I run:

$ asciidoctor -b docbook5 -d book -o out.xml source.txt

There is a built-in attribute xmlns, but it seems to be for docbook 4.5.

The reason I want to use XInclude is to include some xml files from Docinfo files and Passthrough Blocks

Upvotes: 1

Views: 250

Answers (1)

uroesch
uroesch

Reputation: 181

With a bit of research inside the asciidoctor code it quickly became clear that the part you'd like to modify is fairly static. See asciidoctor/converter/docbook5.rb Line 44 for more info.

The best approach is to create a postprocessor extension which modifies the output. The example below is just to show a possible implementation.

Create a file with the following content and call it docbook_postprocessor.rb.

class Docbook5XiPostprocessor < Asciidoctor::Extensions::Postprocessor
  def process document, output
    if document.basebackend? 'docbook'
      input_regex = %r{^(<.*xmlns:xl="http://www.w3.org/1999/xlink") (version="5.0".*>)}
      replacement = %(\\1 xmlns:xi="http://www.w3.org/2001/XInclude" \\2)
      output = output.sub(input_regex, replacement)
    end
    output
  end
end

Asciidoctor::Extensions.register do
  postprocessor Docbook5XiPostprocessor
end

Note: The above extension is for the sake of brevity placed in the same directory as the asciidoctor source file called source.adoc.

The run the asciidoctor command with the -r ./docbook_postprocessor.rb parameters.

$ asciidoctor -r ./docbook_postprocessor.rb -b docbook5 -d book -o - source.adoc  
<?xml version="1.0" encoding="UTF-8"?>
<?asciidoc-toc?>
<?asciidoc-numbered?>
<book
  xmlns="http://docbook.org/ns/docbook"
  xmlns:xl="http://www.w3.org/1999/xlink"
  xmlns:xi="http://www.w3.org/2001/XInclude"
  version="5.0"
  xml:lang="en">
<info>
<title>test</title>
<date>2020-12-19</date>
</info>
</book>

* Above output has been slightly reformatted to eliminate the scrollbar

Creating ruby gem with the above code for easier distribution is a task left to the reader.

Upvotes: 1

Related Questions