2010-10-22 90 views
2

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

如果没有看到示例XML,很难诊断。您确定文档元素上存在指定的元素吗? – 2010-10-22 12:17:48

+0

@Mads:提供的示例:) – 2010-10-22 12:22:22

+0

XPath表达式在哪里? – 2010-10-22 12:30:15

回答

1

如果只是用@myattribute,它会寻找(附加到上下文节点是属性在这种情况下,该文件元件)。

  • 如果你正试图评估属性是否文档中的任何位置,那么你必须改变你的轴在XPATH。

  • 如果你正试图评估属性是附加到特定元素,那么你需要改变你的环境(即不是文档元素,但Element2元素)。

这里有两个可能的解决方案:

  1. 如果您使用XPath表达式//@Myattribute它会扫描整个文件寻找该属性。

  2. 如果将您的上下文更改为Element2元素而不是文档元素,则会找到@Myattribute

+0

我试图找到文档中的任何地方的属性... – 2010-10-22 12:41:01

+0

我应该传递给XAp_get_attribute_in_set以获得属性考虑我以前的评论? – 2010-10-22 12:43:10

+0

'// @ Myattribute' – 2010-10-22 12:47:39

1

如果您知道您的节点是“String”类型,则可以直接使用S_compute_xpath()函数。 例子:

TiXmlString ts = proc.S_compute_xpath(); 

然后,你可以通过使用ts.c_str()转换ts在 “规范” 的字符串。 它的工作原理要么属性与元素,但如果赶上元素你添加在XPath表达式底部的功能文本(),像

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

此外,我认为你必须只包括一个类型为“root”的节点。 您的XML将不得不像

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

Paride。