XMLファイルからデータを取得するためのパーサーに取り組んでいます。libxml2を使用してデータを抽出しています。ノードから属性を取得できません。nb_attributes
属性の数を取得することしかできませんでした。
6 に答える
joostk は属性->子を意味し、次のようなものを与えたと思います:
xmlAttr* attribute = node->properties;
while(attribute)
{
xmlChar* value = xmlNodeListGetString(node->doc, attribute->children, 1);
//do something with value
xmlFree(value);
attribute = attribute->next;
}
それがあなたのために働くかどうか見てください。
単一の属性だけが必要な場合は、xmlGetPropまたはxmlGetNsPropを使用します。
属性が 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
メソッドを使用することでした。@property
これらは XPath 式を評価するため、構文を使用する必要があります。
例えば:
std::string get_property(xmlpp::Node *const &node) {
return node->eval_to_string("@property")
}