簡體   English   中英

如何從libxml2中的節點獲取屬性

[英]How to get attributes from a node in libxml2

我正在使用解析器從XML文件獲取數據。 我正在使用libxml2提取數據。 我無法從節點獲取屬性。 我只找到nb_attributes來獲取屬性計數。

我認為joostk的意思是attribute-> children,給出如下內容:

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

看看是否適合您。

如果只需要單個屬性,請使用xmlGetPropxmlGetNsProp

我想我發現了為什么您只有1個屬性(至少它發生在我身上)。

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

我的解決方案是檢查節點類型(元素為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行。

嘗試類似:

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);
}

如果使用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);

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

例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM