2007年4月17日星期二

网络视频频道源RSS(XML)文件读取

(任何引用请注明:转载于美人山下http://www.beautyhill.blogspot.com)
    如果我没有领会错的话,RSS是基于XML上的一个较高层应用协议;除了新闻可以“RSS订阅”以外,某些网络视频厂商的频道列表也可以进行此操作。例如PPLive频道订阅PPStream频道订阅等。我对RSS没什么心得,但谈到XML却能略知一二。
    对XML这样成熟的标记语言而言,大多数编程工具厂商都会有专门的组件、类库进行处理。在vs2005中,通过XmlDocument类,可以有效的操作相应的XML文档。
    操作XML文档无非是读取、写入等。如何取得某个节点,读取节点属性或是值;如何创建节点,写入节点属性或是值等等,这些基本的动作,一般来说完全可以满足编程人员的需要。

    以下代码演示了频道读取工作:
private static void loadChannels(string xmlFilePath, string itemNode, string manufactureNode,
string nameNode, string catalogNode, char splitor, string authorNode, string linkNode) {
try {
System.Xml.XmlDocument xd = new System.Xml.XmlDocument();
xd.Load(xmlFilePath);
foreach (System.Xml.XmlNode channelNode in xd.GetElementsByTagName(itemNode)) {
System.Xml.XmlDocument xdChannel = new System.Xml.XmlDocument();
xdChannel.LoadXml(channelNode.OuterXml);
string manufacture;
if (xdChannel.GetElementsByTagName(manufactureNode).Count == 0)
manufacture = manufactureNode;
else
manufacture = xdChannel.GetElementsByTagName(manufactureNode)[0].InnerText;
string str = xdChannel.GetElementsByTagName(catalogNode)[0].InnerText;
string[] catalogs = str.Split(splitor);
string name = xdChannel.GetElementsByTagName(nameNode)[0].InnerText,
author = xdChannel.GetElementsByTagName(authorNode)[0].InnerText;
string link = xdChannel.GetElementsByTagName(linkNode)[0].InnerText;
foreach (string catalog in catalogs) {
Channel.addChannel(manufacture, catalog, name, author, link);
}
}
}
catch (Exception E) {
MessageBox.Show("加载频道失败!\n" + E.Message, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}

    以下代码演示了频道保存工作:
public static void SaveFavorites() {
try {
string path = "PPMMConfig.xml";
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
System.Xml.XmlNode root = null;
if (System.IO.File.Exists(path)) {
xmlDoc.Load(path);
root = xmlDoc.DocumentElement;
}
else {
//加入XML的声明段落
xmlDoc.AppendChild(xmlDoc.CreateNode(System.Xml.XmlNodeType.XmlDeclaration, "", ""));
root = xmlDoc.CreateNode(System.Xml.XmlNodeType.Element, "PPMM", "");
xmlDoc.AppendChild(root);
}
System.Collections.IEnumerator ie = Channel.favorites.Keys.GetEnumerator();
System.Xml.XmlNode node = root.SelectSingleNode("Favorites");
if (node == null) {
node = xmlDoc.CreateNode(System.Xml.XmlNodeType.Element, "Favorites", "");
root.AppendChild(node);
}
node.RemoveAll();
while (ie.MoveNext()) {
Channel channel = (Channel)(Channel.favorites[ie.Current.ToString()]);
System.Xml.XmlElement xe = xmlDoc.CreateElement("Channel");
xe.SetAttribute("name", channel.Name);
xe.SetAttribute("catalog", channel.Catalog);
xe.SetAttribute("manufacture", channel.Manufacture);
xe.SetAttribute("author", channel.Author);
xe.SetAttribute("link", channel.Link);
node.AppendChild(xe);
}
xmlDoc.Save(path);
}
catch (Exception E) {
System.Windows.Forms.MessageBox.Show("保存我的收藏失败!\n"+E.Message, "警告",
System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
}
}

没有评论: