我正在嘗試編寫一個函數,該函數將使用XPath與TinyXPath庫的文檔中的一組XML節點的屬性,但似乎無法弄清楚。我發現TinyXPath上的文檔也不是非常有啓發性。有人能幫助我嗎?使用XPath與TinyXPath&TinyXML獲取屬性
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
}
}
}
用法:
XMLDocument doc;
std::string attrib;
attrib = doc.GetXPathAttribute("@Myattribute");
示例XML:
<?xml version="1.0" ?>
<Test />
<Element>Tony</Element>
<Element2 Myattribute="12">Tb</Element2>
如果沒有看到示例XML,很難診斷。您確定文檔元素上存在指定的元素嗎? – 2010-10-22 12:17:48
@Mads:提供的示例:) – 2010-10-22 12:22:22
XPath表達式在哪裏? – 2010-10-22 12:30:15