私はいくつかのXMLを持っています:
<Root>
 <Name>Eding</Name>
 <Roll>15</Roll>
 <xyz:Address>25, Brigton,SA</xyz:Address>
</Root>
xyz名前空間が定義されていないため、この xml は無効です。そこで、xslt を使用してルートに名前空間を追加したいと思います。
どうやってやるの?
XSLT は、名前空間が整形式の XML のみを入力として受け取ります。したがって、入力が名前空間の整形式でない場合、XSLT で問題を解決することはできません。
これを解決する 1 つの方法は、外部の (解析された) 一般的なエンティティを使用することです。
名前空間プレフィックスを宣言する XML ドキュメントで無効な XML ファイルを「ラップ」xyzし、外部エンティティを使用してファイルのコンテンツを含めることができます。次に、ファイルを変換してラップされたコンテンツを削除し、目的の出力を生成します。
この例では、サンプル ファイルはfragment.xml. wrapperファイルを指す外部エンティティを定義し、要素内でそれを参照しました。wrapper要素にはxyz名前空間プレフィックスが定義されています。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE wrapper [
<!ENTITY otherFile SYSTEM "fragment.xml">
]>
<wrapper xmlns:xyz="http://stackoverflow.com/questions/12024763/how-can-i-add-a-namespace-xmlnsxyz-to-an-xml-document-using-xslt">
&otherFile;
</wrapper>
XML パーサーで解析すると、ドキュメントは次のように「認識」されます。
<wrapper xmlns:xyz="http://stackoverflow.com/questions/12024763/how-can-i-add-a-namespace-xmlnsxyz-to-an-xml-document-using-xslt">
<Root>
    <Name>Eding</Name>
    <Roll>15</Roll>
    <xyz:Address>25, Brigton,SA</xyz:Address>
</Root>
</wrapper>
次に、テンプレートで変更された恒等変換wrapperを使用して要素を削除します。
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    version="1.0">
    <!--identity template to copy all content forward by default -->
    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>
    <!--remove the "wrapper" element, then process the rest of the content -->
    <xsl:template match="/wrapper">
        <xsl:apply-templates/>
    </xsl:template>
</xsl:stylesheet>
次の出力を生成します。
<?xml version="1.0" encoding="UTF-8"?>
<Root xmlns:xyz="http://stackoverflow.com/questions/12024763/how-can-i-add-a-namespace-xmlnsxyz-to-an-xml-document-using-xslt">
    <Name>Eding</Name>
    <Roll>15</Roll>
    <xyz:Address>25, Brigton,SA</xyz:Address>
</Root>