首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将XML命名空间添加到ruby中的现有文档

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

Stack Overflow用户
提问于 2009-03-08 08:04:29
回答 1查看 1.1K关注 0票数 1

我需要将一个元素添加到一个现有的XML文档中,该文档使用了原始文档中不存在的名称空间。我该怎么做呢?

理想情况下,我希望使用REXML来实现可移植性,但是任何通用的XML库都可以。理想的解决方案应该是巧妙地处理名称空间冲突。

我有一个xml文档,如下所示:

代码语言:javascript
运行
复制
<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>

并添加:

代码语言:javascript
运行
复制
<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>

产生等同于:

代码语言:javascript
运行
复制
<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>
EN

回答 1

Stack Overflow用户

发布于 2009-03-08 08:32:45

事实证明,这是一个愚蠢的问题。如果初始文档和要添加的元素在内部是一致的,那么名称空间就没问题。因此,这相当于最终文档:

代码语言:javascript
运行
复制
<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创建这个最终文档,只需:

代码语言:javascript
运行
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/623255

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档