Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function. in HTMLAgilityPack

c# html html-agility-pack

Question

I have following contents in Html Document

 <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>

I have to change the value of <dc:date> attribute's value to current date. I am using HtmlAgilityPack and the code as below

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);

But when i tried to convert i am getting this error Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function. How to change its value ?

Popular Answer

It seems that HtmlAgilityPack doesn't support XPath containing prefix.

If your html document is well-formed (valid xml), you can use XDocument or XmlDocument, both support namespace/prefix.

For example, to get <cd:date> element from sample xml above using 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");


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why