我如何添加元素?

时间:2015-06-19 19:50:39

标签: ruby nokogiri

我这样做:

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

然而,@xml仍然没有我的目标。我该怎么做才能更新原始@xml

2 个答案:

答案 0 :(得分: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中不存在targets,则

[]将是./target(实际上是空的NodeSet)。您无法将节点附加到[],因为NodeSet不知道您正在谈论的内容,从而导致undefined method 'children=' for nil:NilClass (NoMethodError)异常。

相反,您必须找到要插入节点的特定位置。 at对此有好处,因为它只找到第一个位置。当然,如果要查找多个位置来修改某些内容,请使用search,然后迭代返回的NodeSet并根据返回的各个节点进行修改。

答案 1 :(得分:0)

我结束这样做,工作正常。

Order.findAll({
    where: { id: 1 },
    include: [
      { model: Item, where: sequelize.and({'active' : true }) }
    ]
}).then(function(order) {
    callback(null, order);
});
相关问题