Преобразование HTML в XML - C#
Формулировка задачи:
Подскажите пожалуйста как такое можно сделать средствами .NET, пытаюсь найти объект HTMLDOM, но пока тщетно, а то бы через объектную модель перегнал.
Решение задачи: «Преобразование HTML в XML»
textual
Листинг программы
using System;
using System.IO;
using mshtml;
using System.Xml;
class Html2Xml
{
static void Main()
{
StreamReader srReadToEnd = new StreamReader((System.IO.Stream)File.OpenRead('test.html'), System.Text.Encoding.GetEncoding('windows-1251'));
string html;
html = srReadToEnd.ReadToEnd();
srReadToEnd.Close();
IHTMLDocument2 document = new HTMLDocumentClass();
document.write(html);
XmlDocument doc = new XmlDocument();
XmlNode root = doc.CreateElement('document');
getChild((XmlNode)root, (IHTMLDOMNode)document.body.parentElement);
doc.AppendChild(root);
Console.Write(root.OuterXml);
}
static void getChild(XmlNode node, IHTMLDOMNode domnode)
{
string nodeName = domnode.nodeName.ToLower();
if(nodeName == '#comment')
{
XmlNode comment = node.OwnerDocument.CreateNode(XmlNodeType.Comment, '', '');
comment.InnerText = domnode.nodeValue.ToString().Replace('--', '=='); // побочный эффект
node.AppendChild(comment);
}
else if(nodeName == '#text')
{
XmlNode text = node.OwnerDocument.CreateNode(XmlNodeType.Text, '', '');
text.InnerText = domnode.nodeValue.ToString();
node.AppendChild(text);
}
else if(nodeName.IndexOf('/') >= 0)
{
XmlNode comment = node.OwnerDocument.CreateNode(XmlNodeType.Comment, '', '');
comment.InnerText = '[ERROR]' + nodeName + '[/ERROR]';
node.AppendChild(comment);
//Console.WriteLine('ERROR: ' + nodeName);
}
else
{
XmlNode nodeCurrent = node.OwnerDocument.CreateElement(nodeName);
IHTMLAttributeCollection collectionAttr = (IHTMLAttributeCollection)domnode.attributes;
if(collectionAttr != null)
{
for(int i = 0; i < collectionAttr.length; i ++)
{
object index = i;
IHTMLDOMAttribute attribute = (IHTMLDOMAttribute)collectionAttr.item(ref index);
if(attribute.nodeValue != null && attribute.nodeValue.ToString() != '')
{
XmlAttribute attr = node.OwnerDocument.CreateAttribute(attribute.nodeName.ToLower());
attr.Value = attribute.nodeValue.ToString().Replace('about:blank', ''); // побочный эффект
nodeCurrent.Attributes.Append(attr);
}
}
}
IHTMLDOMChildrenCollection collection = (IHTMLDOMChildrenCollection)domnode.childNodes;
for(int i = 0; i < collection.length; i ++)
{
getChild((XmlNode)nodeCurrent, (IHTMLDOMNode)collection.item(i));
}
node.AppendChild(nodeCurrent);
}
}
}