set tag attribute and add plain text content to the tag using nokogiri builder (ruby)

前端 未结 1 1150
长发绾君心
长发绾君心 2021-02-04 04:34

I am trying to build XML using Nokogiri with some tags that have both attributes and plain text inside the tag. So I am trying to get to this:



        
1条回答
  •  北荒
    北荒 (楼主)
    2021-02-04 04:49

    There are two approaches you can use.

    Using .text

    You can call the .text method to set the text of a node:

    builder = Nokogiri::XML::Builder.new { |xml|
      xml.Transaction("requestName" => "OrderRequest") do
        xml.Option("b" => "hive"){ xml.text("hello") }
      end
    }
    

    which produces:

    
    
      
    
    

    Solution using text parameter

    Alternatively, you can pass the text in as a parameter. The text should be passed in before the attribute values. In other words, the tag is added in the form:

    tag "text", :attribute => 'value'
    

    In this case, the desired builder would be:

    builder = Nokogiri::XML::Builder.new { |xml|
      xml.Transaction("requestName" => "OrderRequest") do
        xml.Option("hello", "b" => "hive")
      end
    }
    

    Produces the same XML:

    
    
      
    
    

    0 讨论(0)
提交回复
热议问题