0

你好 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 中的上述格式中。

4

1 回答 1

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
于 2014-05-26T07:43:48.347 回答