xml - 将 XML 命名空间添加到 ruby​​ 中的现有文档

标签 xml ruby namespaces rexml

我需要向现有 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/

相关文章:

ruby - 是否可以使用 Rspec 为无限循环问题编写规范?,Ruby

javascript - 需要建议...Javascript OOP/命名空间

java - 如何像此应用程序中那样保持 ImageView 的纵横比? [Android,ImageView,长宽比,ScrollView]

.net - 在 XML 中转义大括号

xml - 如何? xmlstarlet 通过 id 提取 HTML 数据

ruby - 如何获取绑定(bind)中所有变量的列表?

ruby - 为什么我用递归得到 "stack level too deep"?

R 从命名空间选择性导入

c++ - 使用运算符重载时,难以在命名空间内分离类的 header /源

ios - 如何使用 xmlParser 在 iOS 中解析 xml 数组