2010-10-22 193 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。