Ruby에서 XML 태그를 구문 분석할 때 모든 콘텐츠의 합계를 어떻게 얻나요?

StackOverflow https://stackoverflow.com/questions/951220

  •  11-09-2019
  •  | 
  •  

문제

다음과 같은 XHTML이 있습니다(그러나 실제로는 모든 XML이 가능합니다).

<h1>
  Hello<span class='punctuation'>,</span>
  <span class='noun'>World<span class='punctuation'>!</span>
</h1>

전체 내용을 어떻게 얻을 수 있나요? <h1/> Ruby의 문자열로?다음과 같이:

assert_equal "Hello, World!", h1_node.some_method_that_aggregates_all_content

XML 프레임워크(노코기리, libxml-루비, &c.) 이런 종류의 기능이 내장되어 있나요?그렇지 않다면 Y-Combinator가 해당 작업에 적합한 도구일 수 있다고 생각하지만 그것이 어떤 모습일지는 잘 알 수 없습니다.

도움이 되었습니까?

해결책

Nokogiri를 사용하면 다음을 요청할 수 있습니다. text 노드의.하지만 그렇게 할 때 내가 보는 문제는 해당 노드에 있는 모든 공백과 줄 바꿈이 반환되므로 이를 제거하는 것이 좋습니다(이 예에서 수행한 것보다 더 나은 방법일 수 있음).

다음은 샘플입니다.

def test_nokogiri_text
  value = Nokogiri::HTML.parse(<<-HTML_END)
    "<h1>
      Hello<span class='punctuation'>,</span>
      <span class='noun'>World<span class='punctuation'>!</span>
     </h1>"
  HTML_END

  h1_node = value.search("h1").first
  assert_equal("Hello, World!", h1_node.text.split(/\s+/).join(' ').strip)
end

다른 팁

Nokogiri 's nokogiri :: xml :: node#컨텐츠 할 것입니다 :

irb(main):020:0> node
=> <h1>
  Hello<span class="punctuation">,</span>
  <span class="noun">World<span class="punctuation">!</span>
</span>
</h1>
irb(main):021:0> node.content
=> "\n  Hello,\n  World!\n\n"
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top