Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
60 views
in Technique[技术] by (71.8m points)

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>
question from:https://stackoverflow.com/questions/65892047/how-to-use-rs-xml-package-to-write-an-xml-document-in-rss-format

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...