如何解析属性值不在引号

时间:2016-06-22 14:27:35

标签: c# xml

我的XML看起来像这样

<DIV id=MyID01 title="" style="HEIGHT: 100px; WIDTH: 200px;">
<OBJECT onmousedown=BodyMouseDown() id="Viewer" classid=CLSID:E9DAF39B-9CFF-451A-B777-856184C7D516></OBJECT></DIV>

由于MyID01不在引号中,因此当我将其作为XML加载时会出错。 与onmousedoun和classid属性相同。 如何以编程方式将“引号”添加到属性值?我正在考虑正则表达式,但想知道我是否有其他方法。

由于

1 个答案:

答案 0 :(得分:1)

我会使用像HtmlAgilityPack这样的html解析器将此html转换为带引号的属性值语法:

Install-Package HtmlAgilityPack

HtmlAgilityPack 添加到您的项目中,然后您可以执行以下示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;


namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            var html = new HtmlDocument();
            html.Load("C:\\test\\test.html");
            html.OptionOutputAsXml = true;
            System.IO.StringWriter sw = new System.IO.StringWriter();
            System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(sw);
            html.Save("C:\\test\\test.xml");
        }
    }
}

这是我在test.xml文件中得到的结果:

<?xml version="1.0" encoding="iso-8859-1"?>
<div id="MyID01" title="" style="HEIGHT: 100px; WIDTH: 200px;">
  <object onmousedown="BodyMouseDown()" id="Viewer" classid="CLSID:E9DAF39B-9CFF-451A-B777-856184C7D516"></object>
</div>

请注意, HtmlAgilityPack 保存功能提供了许多从解析器获取xml的不同方法。

相关问题