在R中选择特定的XML节点?

时间:2011-04-07 20:39:07

标签: xml r

我在XML中使用R包来解析具有以下结构的XML文件。

 <document id="Something" origId="Text">
    <sentence id="Something" origId="thisorig" text="Blah Blah.">
    <special id="id.s0.i0" origId="1" e1="en1" e2="en2" type="" directed="True"/>
    </sentence>
     <sentence id="Something" origId="thisorig" text="Blah Blah.">
      </sentence>
</document>

我想在一个变量中选择其中包含</special>标记的节点,在其他变量中选择不包含</special>标记的节点。

是否可以使用R来完成任何指针/答案将非常有帮助。

2 个答案:

答案 0 :(得分:6)

我添加了一些案例来测试异常:

<document id="Something" origId="Text">
    <sentence id="Something" origId="thisorig" text="Blah Blah.">
    <special id="id.s0.i0" origId="1" e1="en1" e2="en2" type="" directed="True"/>
    </sentence>
    <sentence id="Else" origId="thatorig" text="Blu Blu.">
      <special id="id.s0.i1" origId="1" e1="en1" e2="en2" type="" directed="True"/>
    </sentence>
     <sentence id="Something" origId="thisorig" text="Blah Blah.">
       <notso id = "hallo" />
      </sentence>
     <sentence id="Something no sentence" origId="thisOther" text="Blah Blah.">
      </sentence>
</document>

library(XML)
doc = xmlInternalTreeParse("sentence.xml")
hasSentence = xpathApply(doc, "//sentence/special/..")
xpathApply(doc, "/document/sentence[not(child::special)]")

答案 1 :(得分:1)

解析xml树,使用xpath指定节点的位置。

doc <- xmlTreeParse("test.xml", useInternalNodes = TRUE)
special_nodes <- getNodeSet(doc, "/document//special")
相关问题