【问题标题】:How I can add an element?如何添加元素?
【发布时间】:2015-06-20 20:21:42
【问题描述】:

我正在这样做:

targets = @xml.xpath("./target")
if targets.empty?
  targets << Nokogiri::XML::Node.new('target', @xml)
end

但是@xml 仍然没有我的目标。我该怎么做才能更新原来的@xml

【问题讨论】:

  • this question 回答你的问题了吗?
  • 您确实应该添加与您的代码匹配的示例 XML,以及您期望的 XML 应该是什么样子。不要让我们拼凑样本数据。

标签: ruby nokogiri


【解决方案1】:

比这容易得多:

require 'nokogiri'

doc = Nokogiri::XML(<<EOT)
<root>
  <node>
  </node>
</root>
EOT

doc.at('node').children = '<child>foo</child>'
doc.to_xml
# => "<?xml version=\"1.0\"?>\n<root>\n  <node><child>foo</child></node>\n</root>\n"

children= 足够聪明,可以看到您传入的内容,并会为您完成肮脏的工作。所以只需使用一个字符串来定义新节点并告诉 Nokogiri 在哪里插入它。


doc.at('node').class   # => Nokogiri::XML::Element
doc.at('//node').class # => Nokogiri::XML::Element

doc.search('node').first   # => #<Nokogiri::XML::Element:0x3fd1a88c5c08 name="node" children=[#<Nokogiri::XML::Text:0x3fd1a88eda3c "\n  ">]>
doc.search('//node').first # => #<Nokogiri::XML::Element:0x3fd1a88c5c08 name="node" children=[#<Nokogiri::XML::Text:0x3fd1a88eda3c "\n  ">]>

search 是通用的“查找节点”方法,它将采用 CSS 或 XPath 选择器。 at 等价于 search('some selector').firstat_cssat_xpathat 的特定等价物,正如 cssxpathsearch。如果需要,请使用特定版本,但通常我使用通用版本。


你不能使用:

targets = @xml.xpath("./target")
if targets.empty?
  targets << Nokogiri::XML::Node.new('target', @xml)
end

如果 DOM 中不存在 ./targettargets 将是 [](实际上是一个空的 NodeSet)。您不能将节点附加到 [],因为 NodeSet 不知道您在说什么,从而导致 undefined method 'children=' for nil:NilClass (NoMethodError) 异常。

相反,您必须找到要插入节点的特定位置。 at 非常适合,因为它只找到第一个位置。当然,如果您想查找多个位置来修改某些内容,请使用 search 然后遍历返回的 NodeSet 并根据返回的各个节点进行修改。

【讨论】:

  • 用xpath不行吗?问题是我在@xml 上收到一个 <:xml::element:> 并且可以修改它...
  • 使用xpathcssat 或任何“查找节点”方法都没有关系。重要的是你如何添加它。
  • 我选择你的答案是正确的,因为你提供了很多有用的信息,但请检查你认为这样做有什么缺点的答案?
  • 试试看。我认为它不会起作用,但您需要了解原因。
【解决方案2】:

我结束了,工作正常。

targets = @xml.xpath("./target")
if targets.empty?
  targets << Nokogiri::XML::Node.new('target', @xml)
  @xml.add_child(targets.first)
end

【讨论】:

    猜你喜欢
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 2019-04-12
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多