I have an xml file and want to know the count of a specific node using R. My xml looks something like below. The node count should be 4. I'm using the xml2
package. Notice there's another element, <tag>
, at the same level that I don't want to count.
I appreciate the help. Thanks!
<root>
<node>
<string>1</string>
<string>2</string>
<string>3</string>
<string>4</string>
</node>
<node>
<string>5</string>
<string>6</string>
<string>7</string>
<string>8</string>
</node>
<node>
<string>9</string>
<string>10</string>
<string>11</string>
<string>12</string>
</node>
<node>
<string>13</string>
<string>14</string>
<string>15</string>
<string>16</string>
</node>
<tag>
<string>17</string>
</tag>
</root>
CodePudding user response:
library(xml2)
length(xml2::xml_find_all(doc, ".//node"))
# [1] 4
doc <- read_xml("<root>
<node>
<string>1</string>
<string>2</string>
<string>3</string>
<string>4</string>
</node>
<node>
<string>5</string>
<string>6</string>
<string>7</string>
<string>8</string>
</node>
<node>
<string>9</string>
<string>10</string>
<string>11</string>
<string>12</string>
</node>
<node>
<string>13</string>
<string>14</string>
<string>15</string>
<string>16</string>
</node>
<tag>
<string>17</string>
</tag>
</root>
")