简体   繁体   中英

How to use R's XML package to write an XML document in RSS format

I'm trying to create an RSS document using R's XML package, but I'm running into trouble. Here is the code I'm using:

df <- data.frame(Labels <- c("Label_1"),
                 Values <- c("Value_1")
)

# CREATE XML FILE
doc = newXMLDoc()
root = newXMLNode("rss", doc = doc)

# WRITE XML NODES AND DATA
channel = newXMLNode("channel", parent = root)
title = newXMLNode("title","Metrics", parent = channel)

for (i in 1:nrow(df)){
  prodNode = newXMLNode("Metric", parent = channel)
  
  # APPEND TO PRODUCT NODE
  newXMLNode("description", df$Labels[i], parent = prodNode)
  newXMLNode("item", df$Values[i], parent = prodNode)
}

# OUTPUT XML CONTENT TO CONSOLE
print(doc)

# OUTPUT XML CONTENT TO FILE
saveXML(doc, file="RSS_Output.xml")

This gives me the following output, which doesn't work with RSS parsers because of, among other things, the wrong root node. Any ideas how to more cleanly generate an RSS file?

<?xml version="1.0"?>
<rss>
  <channel>
    <title>Metrics</title>
    <Metric>
      <description>Label_1</description>
      <item>Value_1</item>
    </Metric>
  </channel>
</rss>

You mixed Metric and item nodes. According to the RSS spec (see https://www.w3schools.com/xml/xml_rss.asp ) a channel contains 1 or more item elements

df <- data.frame(Labels <- c("Label_1"),
                 Values <- c("Value_1")
)

# CREATE XML FILE
doc = newXMLDoc()
root = newXMLNode("rss", doc = doc)

# WRITE XML NODES AND DATA
channel = newXMLNode("channel", parent = root)
title = newXMLNode("title","Metrics", parent = channel)

for (i in 1:nrow(df)){
  prodNode = newXMLNode("item", parent = channel)
  
  # APPEND TO PRODUCT NODE
  newXMLNode("description", df$Labels[i], parent = prodNode)
  newXMLNode("metric", df$Values[i], parent = prodNode)
}

# OUTPUT XML CONTENT TO CONSOLE
print(doc)

# OUTPUT XML CONTENT TO FILE
saveXML(doc, file="RSS_Output.xml")
<?xml version="1.0"?>
<rss>
  <channel>
    <title>Metrics</title>
    <item>
      <description>Label_1</description>
      <metric>Value_1</metric>
    </item>
  </channel>
</rss>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM