Oct 23 2007

Create OPML links with C#

Posted by admin under .NET

This example will use the fetch html title example we created earlier and make it possible to input multiple urls for fetching.

The specific use I needed to achieve was to create  OPML file for Wordpress import - which turned out to not as easy as I though. In WP there is indeed a import OPML file for managing the blogroll - however the problem was that I couldn't find any docs somewhere. Finalöly I found it - can't even remember where - and don't care anymore.

Now - here's the GUI:

In this particular example you need to copy the text and paste it into a file (in Notepad for example) and save. But you could easily create that from the code.

Using the same WebHelper as in the example I mentioned above I feel all code needing some explaination is the OPML stuff:



        private void button1_Click(object sender, EventArgs e)
        {
            System.Text.StringBuilder oBuilder = new StringBuilder();
            oBuilder.Append(@"<?xml version=""1.0"" ?> 
<opml version=""1.0"">
<head>
<title>Links for the site</title> 
<dateCreated>Tue, 23 Oct 2007 12:07:51 GMT</dateCreated> 
</head>
<body>
<outline type=""category"" title=""Blogroll"">
");

            foreach (string s in System.Text.RegularExpressions.Regex.Split(textBox1.Text, "\r\n"))
            {
                string sOne = s.Trim();
                if (sOne.Length > 0)
                {
                    string sFullHtml = WebHelper.FetchHTML(sOne);
                    string sTitle = WebHelper.FetchTitleFromHTML(sFullHtml);
                    string sXML = "<outline text=\"" + sTitle + "\" type=\"link\" xmlUrl=\"\" htmlUrl=\"" + sOne + "\" updated=\"\"/>"; 
                    oBuilder.AppendLine(sXML);
                }
            }
            oBuilder.Append(@"</outline>
  </body>
  </opml>");
            //Fetched the title...
            textBox2.Text = oBuilder.ToString();
        }
    }

 

Tip 1: When splitting on multiple characters (string.Split takes only a single character - use Regex.Split).

I have hardcoded the date as you can see, simple because it has NO value for Wordpress at all.  I also build everything up in a long string (or rather a StringBuilder) but I know the right way would be to use some sort of XmlWriter. I don't care for right way - all I want is to make it work:)

 

Attachments