如何在现有元素周围包装 div



我正在尝试解析现有文档并通过将div包裹在一些现有表单元素周围来修改它。

HTML 表单看起来有点像这样:

<form>
  <label for="username">Username:</label>
  <input name="username" type="text" />
  <label for="password">Password:</label>
  <input name="password" type="password" />
</form>

我可以使用Nokogiri解析文档,并且我知道wrap方法,但是我正在努力掌握如何一次性选择标签和输入标签,然后在这些标签周围包装一个div。 所以我正在寻找的结果是:

<form>
  <div class="form-group">
    <label for="username">Username:</label>
    <input name="username" type="text" />
  </div>    
  <div class="form-group">
    <label for="password">Password:</label>
    <input name="password" type="password" />
  </div>
</form>

我已经尝试了各种XPaths/CSS选择器,并且可以创建一个仅包含标签/输入或整个表单的所有元素的节点集。 有没有办法实现这种修改?

单个 XPath 表达式只能返回单个节点集合,因此为了实现您想要的,您需要进行多个查询,每个查询对应一个labelinput对。

你可以选择一对类似的东西,假设标记表现良好(即每个input前面都有一个label):

//label[1] | //label[1]/following-sibling::input[1]

这将选择第一个label和下一个input。但是,您要选择所有此类对。一种方法是首先选择所有label节点,然后为每个节点label选择它和以下输入。

labels = doc.xpath("//form/label")
labels.each do |l|
  nodes = l.xpath(". | ./following-sibling::input[1]")
  # nodes now contains a label-input pair...
end

我认为wrap方法无法将div元素作为祖先添加到每对,因为它会将元素添加到节点集的每个成员。您可能需要手动移动它们,例如

labels = doc.xpath("//form/label")
labels.each do |l|
  # Select this node and its neighbour.
  nodes = l.xpath(". | ./following-sibling::input[1]")
  # Create the new element, and add it before the label.
  div = Nokogiri::XML::Node.new('div', l.document)
  l.before(div)
  # Move each of the pair onto this new element.
  nodes.each do |n|
    div.add_child(n)
  end
end

请注意,此方法不会移动任何文本节点,因此您可能会发现文档的空格略有变化。

最新更新