R 解析 plist XML

R parsing plist XML

抱歉,编辑时多了一点细微差别!在我提供的示例中,我对我的原始文件进行了过多的简化,因此虽然您的解决方案按原样运行得很漂亮,但如果第二行中有一些额外的东西怎么办?那些似乎摆脱了 xml_find_all(page, "//event"),因为现在它找不到那个节点。我怎样才能让脚本忽略额外的东西(或者也许什么是合并它们的正确搜索词?)谢谢!!!

我是使用 xml 的新手,我有一些语音 xml 文件,我正试图将其扁平化为 R 中的数据帧,但我无法将它们变成使用 XML 包中的一些标准函数阅读。我认为问题在于 plist 格式,因为我尝试应用的其他一些答案不适用于这些文件。

我的文件如下所示(*****第二行已编辑):

<?xml version="1.0" encoding="us-ascii"?>
<event id="111" extraInfo="CivilwarSpeeches" xmlns = "someurl>
    <meta>
            <title>Gettysburg</title>
            <date>1863-11-19</date>
            <organizations>
                    <org>Union</org>
            </organizations>
            <people>
                    <person id="0" type="President">Honest Abe</person>
            </people>
    </meta>
    <body>
            <section name="Address">
                    <speaker id="0">
                            <plist>
                                    <p>Four score and seven years ago</p>
                            </plist>
                    </speaker>
            </section>
    </body>
</event>

最后我想得到一个链接两个部分中的一些信息的数据框,比如

部分|扬声器|扬声器类型|演讲者姓名|正文

地址|0 |总裁|老实人安倍|四分七年前

我发现这个答案很有用,但它似乎仍然无法解压我的数据。 Parsing XML file with known structure and repeating elements

如有任何帮助,我们将不胜感激!

相比 xml 库,我更喜欢使用 xml2 库。
这是一个非常简单的问题。读入数据,解析出需要的属性和节点,assemble到一个数据框中。

library(xml2)
page<-read_xml('<?xml version="1.0" encoding="us-ascii"?>
<event id="111">
         <meta>
         <title>Gettysburg</title>
         <date>1863-11-19</date>
         <organizations>
         <org>Union</org>
         </organizations>
         <people>
         <person id="0" type="President">Honest Abe</person>
         </people>
         </meta>
         <body>
         <section name="Address">
         <speaker id="0">
         <plist>
         <p>Four score and seven years ago</p>
         </plist>     </speaker>     </section>     </body> </event>')


#get the nodes
nodes<-xml_find_all(page, "//event")

#parse the requested information out of each node
Section<- xml_attr(xml_find_first(nodes, ".//section"), "name")
Speaker<- xml_attr(xml_find_first(nodes, ".//person"), "id")
SpeakerType<- xml_attr(xml_find_first(nodes, ".//person"), "type")
SpeakerName<- xml_text(xml_find_first(nodes, ".//person")) 
Body<- xml_text(xml_find_first(nodes, ".//plist/p"))  

#put together into a data.frame
answer<-data.frame(Section, Speaker, SpeakerType, SpeakerName, Body)

代码被设置为解析一系列“事件”节点。为清楚起见,我使用 5 个步骤分别解析出每个请求的信息字段,然后合并到最终数据帧中。
这样做的部分理由是为了在“事件”节点丢失某些请求信息的情况下保持对齐。这可以简化,但如果您的数据集很小,应该不会对性能产生太大影响。