我正在尝试编写一个函数,该函数将使用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