修改XML C ++中的属性值

时间:2015-11-18 11:43:14

标签: c++ xml c++11 libxml2

我有一个XML文件如下:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ConfigData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <MyData>
        <FrontCamera>2</FrontCamera>
        <RearCamera>8</RearCamera>
    </MyData>
</ConfigData>

我需要将属性RearCamera的值从值8修改为16。 我正在使用C ++并拥有libxml2库 我尝试过如下,它没有按预期工作。我错了吗?

xmlDoc* doc = NULL;
xmlNode* root_node = NULL;  
xmlNode *child_node = NULL;
xmlNode *cur_node = NULL;
xmlNode *cur = NULL; 

LIBXML_TEST_VERSION    //!< Macro to check API for match with the DLL we are using 
doc = xmlParseFile("ConfigFile.xml"); //!<parse the file and get the DOM   

if ( doc == NULL)
{

}    
else
{
    root_node = xmlDocGetRootElement(doc);     
    if( root_node != NULL )
        {   
        child_node = root_node->children;                
        unsigned char* cValue;                   
        int iHandedness = 0;

        while(child_node!=NULL)
            {   

                if(!xmlStrcmp(child_node->name,(const xmlChar *)"MyData"))  
                {   
                    cur = child_node->children;   
                    if(NULL!= cur)
                    {
                        for (cur_node = cur; cur_node; cur_node = cur_node->next) 
                        {   
                            if (cur_node->type == XML_ELEMENT_NODE) 
                            {   
                                if(!xmlStrcmp(cur_node->name,(const xmlChar *)"RearCamera"))      
                                {   
                                    cur_node->children->content = (const xmlChar *)(16) ;

                                }
                            }
                        }   
                    }
            }
            child_node = child_node->next;
        }
    }
    xmlSaveFormatFile ("ConfigFile.xml", doc, 1);      
    xmlFreeDoc(doc);        //!< free document
    xmlCleanupParser();     
}       

保存没有发生,代码转储正在发生回溯:

n __vfprintf_chk () from /lib/libc.so.6
#1  0xb5bb7028 in xmlGenericErrorDefaultFunc () from /usr/lib/libxml2.so.2
#2  0xb5bb6e6b in xmlReportError () from /usr/lib/libxml2.so.2
#3  0xb5bb839e in __xmlRaiseError () from /usr/lib/libxml2.so.2
#4  0xb5bb8507 in __xmlSimpleError () from /usr/lib/libxml2.so.2
#5  0xb5be3f81 in __xmlIOErr () from /usr/lib/libxml2.so.2
#6  0xb5be43d7 in xmlIOErr () from /usr/lib/libxml2.so.2
#7  0xb5be4841 in xmlFileOpenW () from /usr/lib/libxml2.so.2
#8  0xb5be7369 in __xmlOutputBufferCreateFilename () from /usr/lib/libxml2.so.2
#9  0xb5be7573 in xmlOutputBufferCreateFilename__internal_alias () from /usr/lib/libxml2.so.2
#10 0xb5c97912 in xmlSaveFormatFileEnc__internal_alias () from /usr/lib/libxml2.so.2
#11 0xb5c979f8 in xmlSaveFileEnc__internal_alias () from /usr/lib/libxml2.so.2

1 个答案:

答案 0 :(得分:0)

似乎您将整数值16放在XML字段中,该字段应为字符串值“16”。

看看libxml2,你似乎必须使用库的函数来改变一个attriute值。

请参阅libxml2 attribute modification C了解如何更改属性值。