我需要向现有 XML 文档添加一个元素,该文档使用原始 namespace 中不存在的 namespace 。我该怎么做呢?
理想情况下,我想使用 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>
最佳答案
事实证明这是一个愚蠢的问题。如果初始文档和要添加的元素在内部是一致的,那么命名空间就可以了。所以这相当于最终的文件:
<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
关于xml - 将 XML 命名空间添加到 ruby 中的现有文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/623255/