Ruby rexml xpath.each不遍历节点

时间:2014-05-26 06:42:02

标签: ruby xml xpath rexml

Hello stackoverflow我一直在使用XML和Ruby。

# rexml


xmlfile = File.new("sample.xml")
xmldoc = REXML::Document.new xmlfile
root = xmldoc.root

# count = 0

XPath.each( xmldoc, "//CRDoc/speech/speaking") do |element| 
    # puts element.attributes['name']
    # puts element.text
    File.open(file_name + "_" + element.attributes['name'] + "-" + year + ".xml", 'a+') do |f|
        f.write("<speaker>" + element.attributes['name'] + "</speaker>")
        f.write("<speech>" + doc.xpath("//speech/speaking[@name='#{element.attributes['name']}']").text + "</speech>" + "\n")
        # f.write("<speaker>" + element.attributes['name'] + "</speaker>")
        # f.write("<speech>" + doc.xpath('//CRDoc/speech/speaking').text + "</speech>" + "\n")
        #f.wrtie("<speech>" + doc.xpath("//CRDoc/speech/speaking[@name=#{element.attributes['name']}]").text + "</speech>" + "\n")
    end
end

以上代码读入将包含在此帖子中的XML文件。我对此代码的问题是它反复选择相同的语音,而不是将XML文件中的每个单独的语音写入新的XML文件。

<?xml version="1.0" encoding="UTF-8"?>
<CRDoc>
  <volume>141</volume>
  <number>1</number>
  <weekday>Wednesday</weekday>
  <month>January</month>
  <day>4</day>
  <year>1995</year>
<chamber>House</chamber>
<pages>H3</pages>
<congress>104</congress>
  <session>1</session>
  <document_title>(Applause, the Members rising.)</document_title>
  <title>TRIBUTE TO THE HONORABLE DONNALD K. ANDERSON</title>
  <recorder>(Mr. BOEHNER asked and was given permission to address the House for 
1 minute.)</recorder>
<speech><speaker name="Mr. BOEHNER">Mr. BOEHNER</speaker>.<speaking name="Mr. BOEHNER">Mr. Clerk, before we proceed with the nominations for 
Speaker of the House, on behalf of Republican Members of the House, we 
want to thank you for your 35 years of service to this institution, and 
your 35 years of service to the American people. You have done your job 
ably on behalf of all Members on both sides of the aisle.</speaking>
  <speaking name="Mr. BOEHNER">And to the other officers of the House, who have served the House so 
ably and the American people so ably, we want to thank them as well for 
their service in this House.</speaking>
  <speaking name="Mr. BOEHNER">Farewell, and best wishes from all of us.</speaking></speech>
 <speech> <speaker name="Mr. FAZIO">Mr. FAZIO</speaker>.<speaking name="Mr. FAZIO">Will the gentleman yield?</speaking></speech>
  <speech><speaker name="Mr. BOEHNER">Mr. BOEHNER</speaker>.<speaking name="Mr. BOEHNER">I yield to my friend, the gentleman from California [Mr. 
Fazio].</speaking></speech>
 <speech> <speaker name="Mr. FAZIO">Mr. FAZIO</speaker>.<speaking name="Mr. FAZIO">I appreciate my friend yielding.</speaking>
  <speaking name="Mr. FAZIO">I, too, would like to add a few words of tribute to our friend.</speaking>
  <speaking name="Mr. FAZIO">When the 103d Congress came to an official close on noon Tuesday, the 
House literally lived on for the next 24 hours in the person of the 
gentleman from Sacramento, CA, the Clerk of the House, Donnald K. 
Anderson. In serving as the first presiding officer for the purpose of 
organizing the 104th Congress, he fulfilled his last ministerial duty 
to this institution. After four successive terms as Clerk and a career 
with the House that began as a Page when Dwight Eisenhower was 
President and Sam Rayburn sat in the Speaker's chair, Donn Anderson now 
leaves a distinguished career of public service.</speaking>
  <speaking name="Mr. FAZIO">On a personal level for many of us in this Chamber, it was only 
natural for Donn Anderson to have been the thread of continuity from 
one Congress to the next. For over 30 years, Donn has embodied every 
good virtue of this House. He has been its memory, its defender, its 
champion and often its conscience. He understood perhaps better than 
anyone here the meaning of the word ``bipartisanship'' and he lived it 
daily in his work with the Members. In his 8 years as the second 
highest ranking officer of the House, he worked tirelessly to move the 
House into the information age and so greatly benefited our 
constituents, the American people.</speaking>
  <speaking name="Mr. FAZIO">As chairman of the Subcommittee on Legislative Appropriations, I 
looked forward to our annual ritual of hearings knowing that I could 
always count on the Clerk for the most splendid testimony. Although 
Donn himself admitted to his preference for Victorian manners, there 
was nothing old-fashioned about the direction of his office. He was 
thoroughly modern in his vision for the future of the House, and he 
fought hard to keep us current with the times. Just as Donn could 
explain the artistic nuances of paintings in the Rotunda, he could just 
as easily give you the technical lowdown of cameras in this Chamber and 
on this floor. As the House moves forward today with the institutional 
reforms and the reorganization, we do so with the solid foundation left 
behind by Donn Anderson.</speaking>
  <speaking name="Mr. FAZIO">Perhaps in parting we can borrow a phrase from our late and great 
Speaker Tip O'Neill. He simply said on so many occasions, ``So long, 
old pal.''</speaking>
  <speaking name="Mr. FAZIO">Thank you, Donn Anderson.</speaking></speech>
</CRDoc>

因此,如果要执行上述代码,则会为示例中的每个发言者创建1个XML文件。然后它将使用相同的语音创建几个语音/扬声器节点。我不明白的是,为什么REXML不会遍历节点并放入每个语音而不是反复播放相同的语音。

我确信有更好的方法来编写代码,但我不熟悉使用XML和XPath。

谢谢!

预期的输出将在BOEHNER.xml文件中:

<speech><speaker name="Mr. BOEHNER">Mr. BOEHNER</speaker>.<speaking name="Mr. BOEHNER">Mr. Clerk, before we proceed with the nominations for 
Speaker of the House, on behalf of Republican Members of the House, we 
want to thank you for your 35 years of service to this institution, and 
your 35 years of service to the American people. You have done your job 
ably on behalf of all Members on both sides of the aisle.</speaking>
  <speaking name="Mr. BOEHNER">And to the other officers of the House, who have served the House so 
ably and the American people so ably, we want to thank them as well for 
their service in this House.</speaking>
  <speaking name="Mr. BOEHNER">Farewell, and best wishes from all of us.</speaking></speech>
  <speech><speaker name="Mr. BOEHNER">Mr. BOEHNER</speaker>.<speaking name="Mr. BOEHNER">I yield to my friend, the gentleman from California [Mr. 
Fazio].</speaking></speech>

正如您所见,Boehner先生在他的XML文件中有4个不同的演讲。这对应于上面发布的sample.xml文件中的4个不同的演讲。

因此,sample.xml文件中的每个语句都会转到一个带有发言者姓名的新文件。

<speaker>Mr. BOEHNER</speaker>
<speech>Mr. BOEHNERMr. Clerk, before we proceed with the nominations for 
Speaker of the House, on behalf of Republican Members of the House, we 
want to thank you for your 35 years of service to this institution, and 
your 35 years of service to the American people. You have done your job 
ably on behalf of all Members on both sides of the aisle.And to the other officers of the House, who have served the House so 
ably and the American people so ably, we want to thank them as well for 
their service in this House.Farewell, and best wishes from all of us.Mr. BOEHNERI yield to my friend, the gentleman from California [Mr. 
Fazio].</speech>

它将采用上述格式。演讲者发表的每一个演讲都将放在[speakername] .xml中。以上述格式。

1 个答案:

答案 0 :(得分:0)

我相信下面的代码会为您提供所需内容:

doc.xpath("//speech/speaking/@name").map(&:text).uniq.each do |name|
  File.open(file_name + "_" + name + "-" + year + ".xml", 'a+') do |f|
    doc.xpath('//speech').each do |speech|
      f.write '<speech>'
      f.write "<speaker name=\"#{name}\">#{name}</speaker>."
      speech.xpath("speaking[@name='#{name}']").each do |speaking|
        f.write "<speaking name=\"#{name}\">#{speaking.text}</speaking>"
      end
      f.write '</speech>'
    end
  end
end

(注意我只使用 nokogiri,而不是rexml ......)

另外,您实际上可以使用 nokogiri来构建XML ...

doc.xpath("//speech/speaking/@name").map(&:text).uniq.each do |name|
  speaker = Nokogiri::XML('<root/>')
  doc.xpath('//speech').each do |speech|
    speech_node = Nokogiri::XML('<speech/>')
    speech.xpath("*[@name='#{name}']").each do |speaking|
      speech_node.root.add_child(speaking)
    end
    speaker.root.add_child(speech_node.root) unless speech_node.root.children.empty?
  end
  File.open(file_name + "_" + name + "-" + year + ".xml", 'a+') do |f|
    f.write speaker.root.children
  end
end