使用 XPath 和 TinyXPath 获取属性 &微小的XML [英] Get attribute using XPath with TinyXPath & TinyXML
问题描述
我正在尝试编写一个函数,该函数将使用 XPath 和 TinyXPath 库获取文档中一组 XML 节点的属性,但我似乎无法弄清楚.我发现 TinyXPath 上的文档也不是很有启发性.有人可以帮助我吗?
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
}
}
}
用法:
XMLDocument doc;
std::string attrib;
attrib = doc.GetXPathAttribute("@Myattribute");
示例 XML:
<?xml version="1.0" ?>
<Test />
<Element>Tony</Element>
<Element2 Myattribute="12">Tb</Element2>
推荐答案
如果你只使用 @myattribute
,它会寻找附加到上下文节点的属性(在这种情况下,文档元素).
If you just use @myattribute
, it will look for that attribute attached to the context node (in this case, the document element).
如果您试图评估该属性是否位于文档中的任何地方,那么您必须在 XPATH 中更改您的轴.
If you are trying to evaluate whether the attribute is anywhere within the document, then you have to change your axis in your XPATH.
如果您尝试评估属性是否附加到特定元素,那么您需要更改上下文(即不是文档元素,而是 Element2
元素).
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:
如果您使用 XPATH 表达式
//@Myattribute
,它将扫描整个文档以查找该属性.
If you use the XPATH expression
//@Myattribute
it would scan the entire document looking for that attribute.
如果您将上下文更改为 Element2
元素,而不是文档元素,则会找到 @Myattribute
.
If you change your context to the Element2
element, rather than the document element, then @Myattribute
would be found.
这篇关于使用 XPath 和 TinyXPath 获取属性 &微小的XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!