2013-01-25 39 views
1

XML值我寫XML文件是這樣的:如何閱讀與空間

<doc> 
    <node1> 
    <value1>aa bb</value1> 
    <value2>cc dd</value2> 
    </node1> 
    <node2> 
    <value1>aaa bbb</value1> 
    <value2>ccc ddd</value2> 
    </node2> 
</doc> 

我嘗試使用minixml庫這個文件解析:

mxml_node_t     *b = tree, *c; //tree is global variable 

    while (b) { 
     if (b && b->type == MXML_ELEMENT) { 
      if(strcmp(b->value.element.name, "value1") == 0) 
      { 
       c = mxmlWalkNext(b, b, MXML_DESCEND); 
       if (c && c->type == MXML_TEXT) 
       { 
        if(c->value.text.string != NULL) 
        { 
         printf("value1=%s"c->value.text.string); 
        } 
       } 
      } 
     } 
     if (b && b->type == MXML_ELEMENT) { 
      if(strcmp(b->value.element.name, "value2") == 0) 
      { 
       c = mxmlWalkNext(b, b, MXML_DESCEND); 
       if (c && c->type == MXML_TEXT) 
       { 
        if(c->value.text.string != NULL) 
        { 
         printf("value2=%s"c->value.text.string); 
        } 
       } 
      } 
     } 
     b = mxmlWalkNext(b, tree, MXML_DESCEND); 
    } 

當我分析,我發現這個文件結果:

value1=aa //the value is not right it must be "aa bb" 
value2=cc 
... 

你有什麼想法,該如何解決我的問題?

回答

0

我使用了下列溶液:

mxml_node_t     *b = tree; //tree is global variable 
char      *tmp,*value1=NULL,*value2=NULL; 

while (b) { 
    if (b && b->type == MXML_TEXT && 
     b->value.text.string && 
     b->parent->type == MXML_ELEMENT && 
     !strcmp(b->parent->value.element.name, "value1")) 
     { 
      if(value1 != NULL) 
      { 
       value1 = strdup(b->value.text.string); 
      } 
      else 
      { 
       tmp = value1; 
       if (asprintf(&value1,"%s %s",tmp, b->value.text.string) == -1) 
       { 
        return -1; 
       } 
       free(tmp); 
       tmp=NULL; 
      } 
     } 
     else 
     { 
      if (value1!=NULL) 
      { 
       printf("value1=%s",value1); 
       free(value1); 
       value1=NULL; 
      } 
     } 
    if (b && b->type == MXML_TEXT && 
     b->value.text.string && 
     b->parent->type == MXML_ELEMENT && 
     !strcmp(b->parent->value.element.name, "value2")) 
     { 
      if(value2 != NULL) 
      { 
       value2 = strdup(b->value.text.string); 
      } 
      else 
      { 
       tmp = value2; 
       if (asprintf(&value2,"%s %s",tmp, b->value.text.string) == -1) 
       { 
        return -1; 
       } 
       free(tmp); 
       tmp=NULL; 
      } 
     } 
     else 
     { 
      if (value2!=NULL) 
      { 
       printf("value2=%s",value2); 
       free(value2); 
       value2=NULL; 
      } 
     } 
    b = mxmlWalkNext(b, tree, MXML_DESCEND); 
}