How do I access value of a particular node of an XML file using R? I am new to R and would also like to know why xmltop[[1]]$IP returns a null. What am I doing wrong?
library('XML')
xmlfile <- xmlTreeParse("E:\\R Scripts\\Data\\Ipdata.xml")
xmltop = xmlRoot(xmlfile)
xmltop[[1]]$IP # return a null value
xmlValue(xmltop[[1]]$IP) # returns NA
XML:
<Response>
<location>
<IP>213.139.122.103</IP>
<CountryCode>FR</CountryCode>
<CountryName>France</CountryName>
<RegionCode/>
<RegionName/>
<City/>
<ZipCode/>
<TimeZone>Europe/Paris</TimeZone>
<Latitude>48.86</Latitude>
<Longitude>2.35</Longitude>
<MetroCode>0</MetroCode>
</location>
<location>
<IP>213.139.122.102</IP>
<CountryCode>INR</CountryCode>
<CountryName>India</CountryName>
<RegionCode/>
<RegionName/>
<City/>
<ZipCode/>
<TimeZone>Chennai</TimeZone>
<Latitude>48.83</Latitude>
<Longitude>2.34</Longitude>
<MetroCode>0</MetroCode>
</location>
</Response>
xml2is pretty nice for parsing, though you'll need your XPath skills. If you want the text contents of all<IP>nodes,library(xml2) ; xml %>% read_xml() %>% xml_find_all('//IP') %>% xml_text()wherexmlis the XML text or a path to the file.