1

元のドキュメントには存在しない名前空間を使用する既存のXMLドキュメントに要素を追加する必要があります。どうすればよいですか?

移植性のためにREXMLを使用するのが理想的ですが、一般的なXMLライブラリであれば問題ありません。理想的な解決策は、名前空間の衝突について賢明です。

私は次のようなxmlドキュメントを持っています:

<xrds:XRDS
 xmlns:xrds="xri://$xrds"
 xmlns="xri://$xrd*($v*2.0)">
    <XRD>
        <Service>
            <Type>http://specs.openid.net/auth/2.0/signon</Type>
            <URI>http://provider.openid.example/server/2.0</URI>
        </Service>
    </XRD>
</xrds:XRDS>

そして追加:

<Service
 xmlns="xri://$xrd*($v*2.0)"
 xmlns:openid="http://openid.net/xmlns/1.0">
    <Type>http://openid.net/signon/1.0</Type>
    <URI>http://provider.openid.example/server/1.0</URI>
    <openid:Delegate>http://example.openid.example</openid:Delegate>
</Service>

次と同等のものを生成します。

<xrds:XRDS
 xmlns:xrds="xri://$xrds"
 xmlns="xri://$xrd*($v*2.0)"
 xmlns:openid="http://openid.net/xmlns/1.0">
    <XRD>
        <Service>
            <Type>http://specs.openid.net/auth/2.0/signon</Type>
            <URI>http://provider.openid.example/server/2.0</URI>
        </Service>
        <Service>
            <Type>http://openid.net/signon/1.0</Type>
            <URI>http://provider.openid.example/server/1.0</URI>
            <openid:Delegate>http://example.openid.example</openid:Delegate>
        </Service>
    </XRD>
</xrds:XRDS>
4

1 に答える 1

1

これはばかげた質問であることがわかりました。最初のドキュメントと追加する要素の両方が内部的に一貫している場合、名前空間は問題ありません。したがって、これは最終的なドキュメントと同等です。

<xrds:XRDS
 xmlns:xrds="xri://$xrds"
 xmlns="xri://$xrd*($v*2.0)">
    <XRD>
        <Service>
            <Type>http://specs.openid.net/auth/2.0/signon</Type>
            <URI>http://provider.openid.example/server/2.0</URI>
        </Service>
        <Service
         xmlns:openid="http://openid.net/xmlns/1.0" 
         xmlns="xri://$xrd*($v*2.0)">
            <Type>http://openid.net/signon/1.0</Type>
            <URI>http://provider.openid.example/server/1.0</URI>
            <openid:Delegate>http://example.openid.example</openid:Delegate>
        </Service>
    </XRD>
</xrds:XRDS>

xmlns最初のドキュメントと要素の両方が、属性を使用してデフォルトの名前空間を定義することが重要です。

最初のドキュメントがにinitial.xmlあり、要素がにあると仮定しelement.xmlます。REXMLを使用してこの最終ドキュメントを作成するには、次のようにします。

require 'rexml/document'
include REXML

document = Document.new(File.new('initial.xml'))
unless document.root.attributes['xmlns']
  raise "No default namespace in initial document" 
end
element = Document.new(File.new('element.xml'))
unless element.root.attributes['xmlns']
  raise "No default namespace in element" 
end

xrd = document.root.elements['XRD']
xrd.elements << element
document
于 2009-03-08T08:32:45.120 に答える