我需要将一个元素添加到一个现有的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>
发布于 2009-03-08 08:32:45
事实证明,这是一个愚蠢的问题。如果初始文档和要添加的元素在内部是一致的,那么名称空间就没问题。因此,这相当于最终文档:
<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
https://stackoverflow.com/questions/623255
复制相似问题