代码之家  ›  专栏  ›  技术社区  ›  s__

R:将XML读取为data.frame

  •  0
  • s__  · 技术社区  · 6 年前

    我面临着这个问题,我读不懂 .xml 归档以使其成为 data.frame 我知道这个问题已经有了很好的答案 here here ,但我不能拒绝回答我的需要,所以很抱歉,如果它是重复的。

    我有一个 .xml文件 这样地:

    <?xml version='1.0' encoding='UTF-8'?>
    <LexicalResource>
      <GlobalInformation label="Created with the standard propagation algorithm"/>
      <Lexicon languageCoding="UTF-8" label="sentiment" language="-">
        <LexicalEntry id="id_0" partOfSpeech="adj">
          <Lemma writtenForm="word"/>
          <Sense>
            <Confidence score="0.333333333333" method="automatic"/>
            <Sentiment polarity="negative"/>
            <Domain/>
          </Sense>
        </LexicalEntry>
            </Lexicon>
    </LexicalResource>
    

    存储在本地。所以我试着这样做:

    library(XML)
        doc<-xmlParse("...\\test2.xml")
        xmldf <- xmlToDataFrame(nodes=getNodeSet(doc,"//LexicalEntry/Lemma/Sense/Confidence/Sentiment"))
    

    但结果是:

    > xmldf
    data frame with 0 columns and 0 rows
    

    所以我试着 xml2 包裹:

    library(xml2)
    pg <- read_xml("...test2.xml")
    
    recs <- xml_find_all(pg, "LexicalEntry")
    
    > recs
    {xml_nodeset (0)}
    

    我缺乏操纵的知识 .xml文件 文件,所以我想我错过了重点。我做错什么了?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Juan Antonio Roldán Díaz    6 年前

    您需要的是属性,而不是值,这就是您使用的方法无法工作的原因,请尝试以下操作:

    data.frame(as.list(xpathApply(doc, "//Lemma", fun = xmlAttrs)[[1]]), 
               as.list(xpathApply(doc, "//Confidence", fun = xmlAttrs)[[1]]), 
               as.list(xpathApply(doc, "//Sentiment", fun = xmlAttrs)[[1]]))
    
      writtenForm          score    method polarity
    1        word 0.333333333333 automatic negative
    

    另一个选项是获取XML的所有属性并用它们构建一个data.frame:

    df <- data.frame(as.list(unlist(xmlToList(doc, addAttributes = TRUE, simplify = TRUE))))
    colnames(df) <- unlist(lapply(strsplit(colnames(df), "\\."), function(x) x[length(x)]))
    df
                                                label writtenForm          score    method 
    1 Created with the standard propagation algorithm        word 0.333333333333 automatic 
      polarity   id partOfSpeech languageCoding     label language
    1 negative id_0          adj          UTF-8 sentiment        -