开发者

Get attribute using XPath with TinyXPath & TinyXML

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 />
<El开发者_StackOverflow社区ement>Tony</Element>
<Element2 Myattribute="12">Tb</Element2>


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.


If you know that your node is of "String" type you can use directly the S_compute_xpath() function. Example:

TiXmlString ts = proc.S_compute_xpath();

Then you can convert ts in a "canonical" string by using ts.c_str(). It works either with attributes as with elements, but if you catch elements you get to add the function text() at the bottom of XPATH expression, like

xpath_processor xproc(doc.RootElement(),"/Documento/Element2/text()");

In addition, i think you have to include only one node of type "root". Your XML will have to look like

<Documento>
        <Test></Test>
        <Element>Tony</Element>
        <Element2 Myattribute="12">Tb</Element2>
</Documento>

Paride.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜