我正在使用
Ruby 1.9.3和最新的Nokogiri宝石.我已经研究了如何使用xpath从xml中提取值并指定元素的路径(?).这是我的XML文件:
<?xml version="1.0" encoding="utf-8"?> <File xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Houses> <Ranch> <Roof>Black</Roof> <Street>Markham</Street> <Number>34</Number> </Ranch> </Houses> </File>
doc = Nokogiri::XML(File.open ("C:\\myfile.xml")) puts doc.xpath("//Ranch//Street")
哪个输出:
<Street>Markham</Street>
这一切都很好,但我需要的是写/替换值.我想使用相同类型的路径样式查找来传递值来替换那里的值.所以我想将街道名称传递给此路径并覆盖那里的街道名称.我一直在互联网上,但只能找到创建新XML或在文件中插入一个全新节点的方法.有没有办法像这样按行替换值?谢谢.
解决方法
你想要
content=
method:
Set the Node’s content to a Text node containing
string
. The string gets XML escaped,not interpreted as markup.
请注意,xpath
返回NodeSet而不是单个节点,因此您需要使用at_xpath或以其他方式获取单个节点:
doc = Nokogiri::XML(File.open ("C:\\myfile.xml")) node = doc.xpath("//Ranch//Street")[0] # use [0] to select the first result node.content = "New value for this node" puts doc # produces XML document with new value for the node