[xml] Re: xpath tutorial example



John Fleck wrote:


I'm adding an xpath example to the tutorial.
Draft posted here:
http://www.inkstain.net/fleck/tutorial/ar01s05.html
Feedback encouraged.

You need a warning label the code is C. I started checking it for C++ style
and ... it failed ;-)

To make the function re-usable, you could make it take the 'xpath' variable
in the arguments.

Thanks for showing xmlNodeListGetString() in action. But how do you know you
don't need to Free its return value?

Is the count variable nodeset->Nr  or nodeset->nodeNr?

I prefer documentation in the form of test cases, but that's just because
I'm one of those screaming zealots who never need to use a debugger.

Below my sig in my feeb C++ effort, and just one of its test cases.

--
  Phlip
            http://www.greencheese.org/HatTrick
  --  My opinions are those of your employer  --


    class
ExPath
{
  public:
    ExPath(std::string const & contents):
        m_context(NULL),
        m_document(xmlParseDoc(BAD_CAST contents.c_str()))
            {
            ATLASSERT(m_document);
            m_context = xmlXPathNewContext(m_document);
            ATLASSERT(m_context);
            m_deleteMe = m_context;
            }
    ExPath(xmlXPathContextPtr context):
        m_document(NULL),
        m_context(context),
        m_deleteMe(NULL)
            {
            ATLASSERT(m_context);
            }

    ExPath(xmlDocPtr document):
        m_document(NULL),
        m_context(xmlXPathNewContext(document))
            {
            ATLASSERT(m_context);
            m_deleteMe = m_context;
            }

   ~ExPath()
        {
        xmlXPathFreeContext(m_deleteMe);
     xmlFreeDoc(m_document);  //  these can survive nulls
        }

        std::string
    operator()(std::string const &path, bool reveal = false) const
        {
        std::string result;
        xmlXPathObjectPtr res (xmlXPathEvalExpression(BAD_CAST path.c_str(),
m_context));

        //  this happens when path is bogus. The lib
        //  emits the error into the console: Read
        //  this to learn what it disliked about your path
        ATLASSERT(res);

        //  TODO  is this string leaking?
        xmlChar * contents = xmlXPathCastToString(res);
        ATLASSERT(contents);

        if (reveal)
            db(quoteMeta_<char>(contents));

        xmlXPathFreeObject(res);  //  TODO  smart wrappers!
        result = reinterpret_cast<char *>(contents);
        xmlFree(contents);
        return result;
        }

  private:
   xmlDocPtr          m_document;
    xmlXPathContextPtr m_context;
    xmlXPathContextPtr m_deleteMe;
};



TEST_(TestCase, WellFormed)  //  tests ExPath alone
    {
    string xml = "<well>formed</well>";
    ExPath aPath(xml);
    CPPUNIT_ASSERT_EQUAL("formed", aPath("/well"));
    }







[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]