我正在尝试添加一个 <EventRouter>
以下 XML 中的元素:
<EventRouters>
<EventRouter id="Important Events to Log File" class="com.cyclonecommerce.events2.router.LogFileRouter" active="true">
<Parameters file="../logs/%nodeName%_events.log"
rollOnStart="false" autoFlush="true"
maxFileSize="2M" maxBackupFiles="5"/>
<MetadataProcessorListRef ref="Messaging"/>
<EventFilterRef ref="Important"/>
</EventRouter>
<EventRouter id="Message Detail to Log File" class="com.cyclonecommerce.events2.router.LogFileRouter" active="false">
<Parameters file="../logs/%nodeName%_message_detail.log"
rollOnStart="true" autoFlush="true"
maxFileSize="2M" maxBackupFiles="5"/>
<MetadataProcessorListRef ref="Messaging"/>
<EventFilterRef ref="Message Detail"/>
</EventRouter>
</EventRouters>
我能够将节点附加到节点集,但是在保存 XML 之后我没有得到我想要的更新的 XML:
require 'nokogiri'
if File.exist?('a.xml')
data = File.read("a.xml")
end
doc = Nokogiri::XML.parse data
doc2=doc.xpath("//EventRouters/EventRouter")
event_router = Nokogiri::XML::Node.new("EventRouter",doc)
event_router['id'] = "some"
param_node = Nokogiri::XML::Node.new("Parameters",doc)
param_node.content = "some content"
event_router << param_node
doc2<< event_router
File.open('test.xml', 'w') do |file|
file.print doc.to_xml
end
改变
doc2=doc.xpath("//EventRouters/EventRouter")
到
doc2 = doc.at_xpath("//EventRouters")
xpath
返回一个数组。您可以使用 at_xpath
获取第一个元素。还要去掉 /EventRouter
,因为我猜你想将另一个“EventRouter”项附加到 EventRouters
我是一名优秀的程序员,十分优秀!