需要命名空间管理器或XsltContext。此查询具有前缀,变量或用户定义的函数。在HTMLAgilityPack中

时间:2014-03-03 06:04:46

标签: c# html html-agility-pack

我在Html文档中有以下内容

 <opf:metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf">
    <dc:title>Book Title</dc:title>
    <dc:language>en-us</dc:language>
    <meta name="cover" content="My_Cover" xmlns="" />
    <dc:identifier id="BookId" opf:scheme="ISBN">123456789</dc:identifier>
    <dc:creator>Author Name</dc:creator>
    <dc:publisher>amazon.com</dc:publisher>
    <dc:subject>amazon.com</dc:subject>
    <dc:date>2014-02-28T00:00:00+05:30</dc:date>
  </opf:metadata>

我必须将<dc:date>属性值的值更改为当前日期。我正在使用HtmlAgilityPack和下面的代码

var html1 = new HtmlAgilityPack.HtmlDocument();
             html1.LoadHtml(OPFFile);

             var links1 = html1.DocumentNode.SelectNodes("opf:metadata");

             foreach (var link in links1)
             {

                 link.Attributes["dc:date"].Value = DateTime.Now.ToString("yyyy-MM-dd");
             }

             var builder1 = new StringBuilder();
             using (var writer = new StringWriter(builder))
             {
                 html1.Save(writer);
             }
             OPFFile = builder1.ToString();
             File.WriteAllText(@"D:\FindImageInFile\FindImageInFile\OPF.html", OPFFile);

但是当我试图转换时,我收到此错误Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function. 如何改变它的价值?

1 个答案:

答案 0 :(得分:3)

似乎是HtmlAgilityPack doesn't support XPath containing prefix

如果您的html文档格式正确(有效的xml),则可以使用XDocumentXmlDocument,两者都支持名称空间/前缀。

例如,要使用<cd:date>从上面的示例xml获取XDocument元素:

var xdoc = XDocument.Parse(OPFFile);
//or if OPFFile is file path use : XDocument.Load(OPFFile);
XNamespace dc = "http://purl.org/dc/elements/1.1/";
var date = (string)xdoc.Root.Element(dc + "date");