Xpath表达式(nokogiri)获取标签的子元素?
Xpath expression (nokogiri) to get tag's child element?
从我的xml,我可以得到这个:
<home>
<creditors>
<count>2</count>
</creditors>
</home>
或者甚至这样:
<home>
<creditors>
<moreThan>2</moreThan>
</creditors>
</home>
我可以使用哪个 xpath 表达式来获取 "<count>2</count>"
而不是只获取 "2" 或获取 "<moreThan>2</moreThan>"
而不是获取 "2" ?
这个 XPath,
//creditors/count
将 select XML 文档中所有 creditors
元素的所有 count
子元素。
根据 OP 在注释中的请求更新 select 同时包含 count
和 moreThan
元素的单个 XPath:
这个 XPath,
//creditors/*[self::count or self::moreThan]
将 select XML 文档中所有 creditors
元素的所有 count
或 moreThan
子元素。
假设你的xpath表达式没问题,你只需要将元素转成字符串即可:
doc.xpath("home/creditors/*").to_s
=> "<count>2</count>"
请检查返回多个元素的查询,以确保它是所需的行为。
从我的xml,我可以得到这个:
<home>
<creditors>
<count>2</count>
</creditors>
</home>
或者甚至这样:
<home>
<creditors>
<moreThan>2</moreThan>
</creditors>
</home>
我可以使用哪个 xpath 表达式来获取 "<count>2</count>"
而不是只获取 "2" 或获取 "<moreThan>2</moreThan>"
而不是获取 "2" ?
这个 XPath,
//creditors/count
将 select XML 文档中所有 creditors
元素的所有 count
子元素。
根据 OP 在注释中的请求更新 select 同时包含 count
和 moreThan
元素的单个 XPath:
这个 XPath,
//creditors/*[self::count or self::moreThan]
将 select XML 文档中所有 creditors
元素的所有 count
或 moreThan
子元素。
假设你的xpath表达式没问题,你只需要将元素转成字符串即可:
doc.xpath("home/creditors/*").to_s
=> "<count>2</count>"
请检查返回多个元素的查询,以确保它是所需的行为。