如何在将RSS转换为Plain XML时正确显示XML

时间:2012-06-08 17:32:24

标签: xml vb.net rss

基本上,我手头有这个RSS提要。我通过以下方式将RSS转换为XmlDocument:

 Public Function GroveHallFromRss() As String
        Dim webClient As System.Net.WebClient = New System.Net.WebClient()
        Dim ourUrl As String = "http://abc.123.org/RSSSyndicator.aspx?type=N&range=currentyear&expire=Y&location=2-7-165&rssid=18"
        Dim stream AS Stream
    stream = webClient.OpenRead(ourUrl)
    Dim xmlDocument AS XmlDocument = new XmlDocument()
        xmlDocument.Load(stream)

        Dim root As XmlNode = xmlDocument.DocumentElement
    Return root.OuterXml.ToString

    End Function

通过上述内容,我可以获取RSS的内容,但它以<string>标记开头,以</string>标记结尾。中间的内容都是简单的文字挤压在一起。

如果我删除OuterXml部分,只是Return root.ToString,我得到以下内容:

  

此XML文件似乎没有任何关联的样式信息   用它。文档树如下所示。          <string>System.Xml.XmlElement</string>

所以我想知道如何将转换后的RSS显示为任何其他具有样式节点的XML文件。 (但不是由浏览器呈现和显示为RSS,而只是样式化的XML)

2 个答案:

答案 0 :(得分:1)

首先,在您当前的代码中没有必要将XML加载到XmlDocument对象中。例如,以下内容完成相同的事情:

Public Function GroveHallFromRss() As String
    Dim webClient As System.Net.WebClient = New System.Net.WebClient()
    Dim ourUrl As String = "http://abc.123.org/RSSSyndicator.aspx?type=N&range=currentyear&expire=Y&location=2-7-165&rssid=18"
    Dim streamReader As StreamReader = New StreamReader(webClient.OpenRead(ourUrl))
    Return streamReader.ReadToEnd()
End Function

但是,这并未回答有关正确缩进文档的问题。要做到这一点,我认为最简单的方法是应用样式表。以下XSLT脚本将使XML文档非常漂亮:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>
  <xsl:strip-space elements="*"/>
  <xsl:template match="/">
    <xsl:copy-of select="."/>
  </xsl:template>
</xsl:stylesheet>

您可以在代码中应用XSLT脚本:

Public Function GroveHallFromRss() As String
    Dim webClient As System.Net.WebClient = New System.Net.WebClient()
    Dim ourUrl As String = "http://abc.123.org/RSSSyndicator.aspx?type=N&range=currentyear&expire=Y&location=2-7-165&rssid=18"
    Dim reader as XmlTextReader = new XmlTextReader(webClient.OpenRead(ourUrl))
    Dim transformer As XslCompiledTransform = New XslCompiledTransform()
    transformer.Load("<?xml version=""1.0"" encoding=""utf-8""?><xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform""><xsl:output method=""xml"" indent=""yes""/><xsl:strip-space elements=""*""/><xsl:template match=""/""><xsl:copy-of select="".""/></xsl:template></xsl:stylesheet>")
    Dim settings As XmlWriterSettings = transformer.OutputSettings
    Dim outputStream As MemoryStream = New MemoryStream()
    Dim xmlWriter As XmlWriter = xmlWriter.Create(outputStream, settings)
    transformer.Transform(reader, Nothing, xmlWriter)
    outputStream.Position = 0
    Dim streamReader As StreamReader = New StreamReader(outputStream)
    Return = streamReader.ReadToEnd()
End Function

答案 1 :(得分:0)

谢谢,实际上我的朋友帮我做了一个小改动。这就是将As String更改为As XmlDocument。做到了。所以“Public Function GroveHallFromRss()As XmlDocument”感谢您的帮助。