проблема с парсером c ++ dom - PullRequest
1 голос
/ 30 марта 2011

Я хочу изменить файл XML. Я использую DOM Parser. Мой XML-файл выглядит следующим образом:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>

<!-- Put site-specific property overrides in this file. -->

<configuration>
<property>
  <name>fs.default.name</name>
  <value> name</value>
  </property>

</configuration>

Я просто хочу удалить узел <value>name</name> и поставить новый узел <value>next</value>. Как я могу это сделать?

Я также написал код на C ++, но я застрял в середине. Что я должен делать? Мой код следующий:

#include<string.h>
#include<iostream>
#include<sstream>
#include<sys/types.h>
#include<unistd.h>
#include<errno.h>
#include<sys/stat.h>
#include "parser.hpp"
using namespace xercesc ;
using namespace std;

GetConfig::GetConfig()
{
XMLPlatformUtils::Initialize();
 TAG_configuration =XMLString::transcode("configuration");
 TAG_property = XMLString::transcode("property");
TAG_value=XMLString::transcode("value");
Tag_name=XMLString::transcode("name");
m_ConfigFileParser=new XercesDOMParser;
}
GetConfig::~GetConfig()
{
 delete m_ConfigFileParser;

XMLString::release( &TAG_configuration );
XMLString::release( &TAG_property );
XMLString::release( &TAG_value );

XMLPlatformUtils::Terminate();
}
void GetConfig :: readConfigFile(string& configFile)
{
 struct stat fileStatus;     
int iretStat = stat(configFile.c_str(), &fileStatus);
   if( iretStat == ENOENT )
          throw ( std::runtime_error("Path file_name does not exist, or path is an empty string.") );
       else if( iretStat == ENOTDIR )
          throw ( std::runtime_error("A component of the path is not a directory."));
       else if( iretStat == ELOOP )
          throw ( std::runtime_error("Too many symbolic links encountered while traversing the path."));
   else if( iretStat == EACCES )
          throw ( std::runtime_error("Permission denied."));
       else if( iretStat == ENAMETOOLONG )
          throw ( std::runtime_error("File can not be read\n"));

       // Configure DOM parser.

       m_ConfigFileParser->setValidationScheme( XercesDOMParser::Val_Never );
       m_ConfigFileParser->setDoNamespaces( false );
       m_ConfigFileParser->setDoSchema( false );
       m_ConfigFileParser->setLoadExternalDTD( false );

    m_ConfigFileParser->parse( configFile.c_str() );

     DOMDocument* xmlDoc = m_ConfigFileParser->getDocument();
      DOMElement* elementRoot = xmlDoc->getDocumentElement();

   DOMNodeList*      children = elementRoot->getChildNodes();

int main()
    {
       string configFile="/home/manish.yadav/Desktop/simple.xml"; 

       GetConfig appConfig;

   appConfig.readConfigFile(configFile);


       return 0;
    }

Теперь я не знаю, как пройти этот документ. Вот мои вопросы:

  • Как мне добраться до <value>?
  • Как я могу изменить значение <value> name</value> на <value> next</value>?

Моя идея состоит в том, чтобы удалить сущность, а затем добавить ее снова с другим значением, но я также не знаю, как это сделать. Пожалуйста, объясните с примером кода или предложите какие-либо другие идеи, как это сделать.

1 Ответ

0 голосов
/ 30 марта 2011

После m_ConfigFileParser->parse( configFile.c_str() ); выполните следующее (учитывая, что «конфигурация» является корневым элементом):

DOMDocument* doc = m_ConfigFileParser.getDocument();
DOMElement* root = dynamic_cast<DOMElement*>( doc->getFirstChild() );
if ( root ) {
  DOMElement* property = dynamic_cast<DOMElement*>( root->getElementsByTagName( "property" )->item( 0 ) );
  if ( property ) {
    DOMElement* value = dynamic_cast<DOMElement*>( property->getElementsByTagName( "value" )->item( 0 ) );
    if ( value ) {
      value->setTextContent( " next" ); // this will update the element named "value"
    }
  }
}
...