简体   繁体   中英

Adding namespace prefix when transforming regular XML into Dublin Core XML

I may very well be missing something obvious, but I'm not clear on how to code my XSLT stylesheet to transform one "regular" XML file to generate a Dublin Core XML file that includes the namespace "dc" prefix on each element. I've looked through a lot of other answers here and can't seem to figure out how to do this. (I'm using msxsl.exe for the transformation.)

For example, I'm trying to turn this line from my original XML document:

    <title>Message received clairaudiently by Mrs. Begg at Lake Pleasant, Fri. March 9, 1945.</title>

...into this (after running it through the XSLT transformation):

<dc:title>Message received clairaudiently by Mrs. Begg at Lake Pleasant, Fri. March 9, 1945.</dc:title>

Here's the stylesheet element I'm using in my XSL file:

    <xsl:stylesheet 
    version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:xlink="http://:www.w3.org/1999/xlink" 
    xmlns:dc="http://purl.org/dc/elements/1.1/">

So my question is, do I have to hard-code the "dc:" prefix into the individual elements in the XSL stylesheet, a la:

<dc:title><xsl:value-of select="title" /></dc:title>

Or is there a way to have the XSL transformation add the prefix to each element automatically?

[I]s there a way to have the XSL transformation add the prefix to each element automatically?

If you want to prefix all elements without exceptions, you don't have to do it manually. For example, if you have an input file like:

Input

<?xml version="1.0"?>
<root>
    <item/>
    <item/>
</root>

apply the following transformation. The stylesheet does not change anything except prefixing all elements with dc: .

Stylesheet

<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:dc="http://purl.org/dc/elements/1.1/">

   <xsl:output method="xml" indent="yes"/>
   <xsl:strip-space elements="*"/>

   <xsl:template match="@*|node()">
      <xsl:copy>
         <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
   </xsl:template>

   <xsl:template match="*">
       <xsl:element name="{concat('dc:',name())}">
           <xsl:apply-templates select="@*|node()"/>
       </xsl:element>
   </xsl:template>

</xsl:stylesheet>

Output

<?xml version="1.0" encoding="utf-8"?>
<dc:root xmlns:dc="http://purl.org/dc/elements/1.1/">
   <dc:item/>
   <dc:item/>
</dc:root>

Note that it is impossible to tell whether this can be integrated into your current stylsheet. Unfortunately, you did not reveal much of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM