7

XMLファイルからデータを取得するためのパーサーに取り組んでいます。libxml2を使用してデータを抽出しています。ノードから属性を取得できません。nb_attributes属性の数を取得することしかできませんでした。

4

6 に答える 6

14

joostk は属性->子を意味し、次のようなものを与えたと思います:

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

それがあなたのために働くかどうか見てください。

于 2009-11-06T22:17:02.730 に答える
9

単一の属性だけが必要な場合は、xmlGetPropまたはxmlGetNsPropを使用します。

于 2011-07-06T22:36:10.903 に答える
4

属性が 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行目まで。

于 2013-12-07T22:03:54.693 に答える
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);
}
于 2009-09-23T14:58:22.997 に答える
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);
于 2014-09-05T12:21:52.807 に答える
0

libxml2 を (C++ で libxml++ を介して) 使用して見つけた最も簡単な方法は、eval_to_XXXメソッドを使用することでした。@propertyこれらは XPath 式を評価するため、構文を使用する必要があります。

例えば:

std::string get_property(xmlpp::Node *const &node) {
    return node->eval_to_string("@property")
}
于 2015-12-12T20:45:53.470 に答える