如何通过 CSS 选择器定位标签,引用同级标签的内容?
我正在编写一个 Ruby 脚本,它将解析和操作一些 XML 文件。我使用 Nokogiri 进行 XML 处理。
我遇到的问题是,有几个像这样的构造:
<USER_ELEMENT>
<NAME>ATTRIBUTE01</NAME>
<VALUE>XXX</VALUE>
</USER_ELEMENT>
我需要设置与特定
。我目前的方法是使用
标记。
xml.css('USER_ELEMENT').find { |node| node.at_css('NAME').text == 'ATTRIBUTEnn'}.at_css('VALUE').content = 'NEW_VALUE'
但它看起来相当丑陋。
我想知道哪种方式是处理这种情况的更干净的方法?
I'm working on a Ruby script that will parse and manipulate some XML files. I'm using Nokogiri for the XML handling.
The problem I have is that there are several constructs like this one:
<USER_ELEMENT>
<NAME>ATTRIBUTE01</NAME>
<VALUE>XXX</VALUE>
</USER_ELEMENT>
I need to set the <VALUE>
tag that's within the same of a particular <VALUE>ATTRIBUEnn</VALUE>
. My current approach is using
xml.css('USER_ELEMENT').find { |node| node.at_css('NAME').text == 'ATTRIBUTEnn'}.at_css('VALUE').content = 'NEW_VALUE'
but it looks rather ugly.
I'm wondering which would be a cleaner way of dealing with the situation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 XPath:
在英语中,XPath 表示:
//USER_ELEMENT
- 在文档中的任何位置查找具有此名称的元素[...]
- 但前提是...NAME="ATTRIBUTE01"
- ...您可以找到包含此文本的子NAME
元素/VALUE
找到一个子NAME
元素 - 现在找到该子元素其中的VALUE
元素Using XPath:
In English, that XPath says:
//USER_ELEMENT
- find elements with this name anywhere in the document[…]
- but only if…NAME="ATTRIBUTE01"
- …you can find a childNAME
element with this text/VALUE
- and now find the childVALUE
elements of these兄弟姐妹的 css 选择器是~:
The css selector for siblings is ~:
我不知道 nokogiri 是否支持 CSS3,但如果支持,这应该可以工作
I don't know if nokogiri supports CSS3, but if it does, this should work