views:

52

answers:

1

I'm trying to write a function that will get me the attribute of a set of XML nodes in a document using XPath with the TinyXPath library, but I cannot seem to figure it out. I find the documentation on TinyXPath is not very enlightening either. Can someone assist me?

std::string XMLDocument::GetXPathAttribute(const std::string& attribute)
{
    TiXmlElement* Root = document.RootElement();
    std::string attributevalue;
    if (Root)
    {
        int pos = attribute.find('@');  //make sure the xpath string is for an attribute search
        if (pos != 0xffffffff)
        {
            TinyXPath::xpath_processor proc(Root,attribute.c_str()); 
            TinyXPath::expression_result xresult = proc.er_compute_xpath();

            TinyXPath::node_set* ns = xresult.nsp_get_node_set(); // Get node set from XPath expression, however, I think it might only get me the attribute??

            _ASSERTE(ns != NULL);
            TiXmlAttribute* attrib = (TiXmlAttribute*)ns->XAp_get_attribute_in_set(0);  // This always fails because my node set never contains anything...
            return attributevalue;  // need my attribute value to be in string format

        }

    }
}

usage:

XMLDocument doc;
std::string attrib;
attrib = doc.GetXPathAttribute("@Myattribute");

sample XML:

<?xml version="1.0" ?>
<Test />
<Element>Tony</Element>
<Element2 Myattribute="12">Tb</Element2>
+1  A: 

If you just use @myattribute, it will look for that attribute attached to the context node (in this case, the document element).

  • If you are trying to evaluate whether the attribute is anywhere within the document, then you have to change your axis in your XPATH.

  • If you are trying to evaluate whether the attribute is attached to a particular element, then you need to change your context (i.e. not the document element, but the Element2 element).

Here are two potential solutions:

  1. If you use the XPATH expression //@Myattribute it would scan the entire document looking for that attribute.

  2. If you change your context to the Element2 element, rather than the document element, then @Myattribute would be found.

Mads Hansen
I'm trying to find attribute anywhere in the document...
Tony
What value should I pass to XAp_get_attribute_in_set to get the attribute taking into account my previous comment?
Tony
`//@Myattribute`
Mads Hansen
It takes only an integer (array index into nodeset..) I don't know beforehand where in my nodeset my attribute might appear
Tony
Sorry, didn't read that part carefully. You don't want to provide that XPATH there(that is what you specify further up). I'm not familiar with the TinyXPATH or TinyXML libraries. If they are 0 based, then 0 is probably what you should pass in. Your issue may not be that line, but that you haven't selected anything, so the set is empty. Verify that `ns` is not null or empty first. If you haven't selected anything, then it won't work.
Mads Hansen