【问题标题】:Add XML namespace to existing document in ruby将 XML 命名空间添加到 ruby​​ 中的现有文档
【发布时间】:2010-10-12 00:23:28
【问题描述】:

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

【问题讨论】:

    标签: xml ruby namespaces rexml


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2011-01-02
      • 2012-06-23
      • 1970-01-01
      • 1970-01-01
      • 2011-11-27
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      相关资源
      最近更新 更多