Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Count number of nodes R, xml2

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>


MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading