System.Xml.XPath.XPathException has an invalid token

14,422

Solution 1

You have a default namespace in your xml which is needed in xpath..

XmlNamespaceManager oManager = new XmlNamespaceManager(new NameTable());
oManager.AddNamespace("ns", "http://api.uclassify.com/1/server/ResponseSchema");
doc.SelectSingleNode("/ns:uclassify/ns:readCalls/ns:classify/ns:classification/ns:class[1]/@p",oManager);

Though I would use LINQ2XML

XDocument doc=XDocument.Load(stream);
var pList=doc.Descendants()
                   .Elements(x=>x.Name.LocalName=="class")
                   .Select(a=>
                         new
                         {
                            className=a.Attribute("className").Value,
                            p=a.Attribute("p").Value
                         });

You can now iterate over pList

foreach(var p in pList)
{
    p.className;
    p.p;
}

Solution 2

Shouldn't you declare the namespace somewhere? The XML response you get has a default namespace xmlns="http://api.uclassify.com/1/server/ResponseSchema".

Also make sure to add a / before @p in your XPath:

/uclassify/readCalls/classify/classification/class[1]/@p
Share:
14,422
Niko
Author by

Niko

Updated on June 05, 2022

Comments

  • Niko
    Niko almost 2 years

    When trying to parse XML I get an exception referencing invalid tokens

    html response from the url:

    <?xml version="1.0" encoding="UTF-8" ?>
    <uclassify xmlns="http://api.uclassify.com/1/server/ResponseSchema" version="1.01">
        <status success="true" statusCode="2000"/>
        <readCalls>
            <classify id="Classify">
            <classification textCoverage="0.849057">
                <class className="negative" p="0.567908"/>
                <class className="positive" p="0.432092"/>
            </classification>
            </classify>
        </readCalls>
    </uclassify>
    

    Code:

    HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
    var stream = myHttpWebResponse.GetResponseStream();
    var reader = new StreamReader(stream);
    string html = reader.ReadToEnd();
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(html);
    string negative = doc.SelectSingleNode("/uclassify/readCalls/classify/classification/class[1]@p").ToString();
    string positive = doc.SelectSingleNode("/uclassify/readCalls/classify/classification/class[2]@p").ToString();
    

    I don't really get why it isn't working. Any help would be appreciated.