2009-07-07 85 views

回答

1

試着這麼做:

xmlNodePtr node; // Some node 
NSMutableArray *attributes = [NSMutableArray array]; 

for(xmlAttrPtr attribute = node->properties; attribute != NULL; attribute = attribute->next){ 
    xmlChar *content = xmlNodeListGetString(node->doc, attribute->children, YES); 
    [attributes addObject:[NSString stringWithUTF8String:content]]; 
    xmlFree(content); 
} 
+0

嗨墊。我發現你的代碼有助於找出屬性的值。但它只給出第一個節點的值。如何獲取下列節點的值。 ??.. 提前致謝。 – NiKKi 2012-06-01 09:31:49

+0

不應該`node-children`成爲`attribute-> children`? – 2013-04-20 09:58:30

+0

是的,它應該:)另見@Matthew Lowe,他早先注意到了錯誤。我已經更新了答案(2.5年後;)) – Joost 2013-04-21 00:22:39

8

我覺得joostk意味着屬性 - >孩子,讓這樣的事情:

xmlAttr* attribute = node->properties; 
while(attribute) 
{ 
    xmlChar* value = xmlNodeListGetString(node->doc, attribute->children, 1); 
    //do something with value 
    xmlFree(value); 
    attribute = attribute->next; 
} 

看看是否能爲你工作。

2

我想我找到了,爲什麼你只得到了1個屬性(至少它發生在我身上)。

問題是我讀了第一個節點的屬性,但接下來是文本節點。不知道爲什麼,但node->屬性給了我一個內存不可讀部分的引用,所以它崩潰了。

我的解決辦法是檢查節點類型(元素1)

我使用的是讀者,所以:

xmlTextReaderNodeType(reader)==1 

整個代碼,你可以從http://www.xmlsoft.org/examples/reader1.c得到它,添加此

xmlNodePtr node= xmlTextReaderCurrentNode(reader); 
if (xmlTextReaderNodeType(reader)==1 && node && node->properties) { 
    xmlAttr* attribute = node->properties; 
    while(attribute && attribute->name && attribute->children) 
    { 
     xmlChar* value = xmlNodeListGetString(node->doc, attribute->children, 1); 
     printf ("Atributo %s: %s\n",attribute->name, value); 
     xmlFree(value); 
     attribute = attribute->next; 
    } 
} 

排隊50

0

如果使用SAX方法startElementNs( ......),這個功能是你在找什麼:

xmlChar *getAttributeValue(char *name, const xmlChar ** attributes, 
      int nb_attributes) 
{ 
int i; 
const int fields = 5; /* (localname/prefix/URI/value/end) */ 
xmlChar *value; 
size_t size; 
for (i = 0; i < nb_attributes; i++) { 
    const xmlChar *localname = attributes[i * fields + 0]; 
    const xmlChar *prefix = attributes[i * fields + 1]; 
    const xmlChar *URI = attributes[i * fields + 2]; 
    const xmlChar *value_start = attributes[i * fields + 3]; 
    const xmlChar *value_end = attributes[i * fields + 4]; 
    if (strcmp((char *)localname, name)) 
     continue; 
    size = value_end - value_start; 
    value = (xmlChar *) malloc(sizeof(xmlChar) * size + 1); 
    memcpy(value, value_start, size); 
    value[size] = '\0'; 
    return value; 
} 
return NULL; 
} 

用法:

char * value = getAttributeValue("atrName", attributes, nb_attributes); 
// do your magic 
free(value); 
0

我發現在C++中使用的libxml2(通過的libxml ++最簡單的方法)是使用eval_to_XXX方法。他們評估XPath表達式,因此您需要使用@property語法。

例如:

std::string get_property(xmlpp::Node *const &node) { 
    return node->eval_to_string("@property") 
} 
相關問題