Trying to get the XML content without spaces with SAX2

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • neisan
    New Member
    • Feb 2008
    • 4

    Trying to get the XML content without spaces with SAX2

    Hi there,

    I'm trying for a while to obtain the XML content of a file without spaces.

    I have a XML file with the following content:

    <script>
    <command>
    <createDocument >
    <name>MyDocumen t</name>
    <type>Text</type>
    </createDocument>
    </command>
    <command>
    <createFile>
    <name>MyFile</name>
    <type>File</type>
    </createFile>
    </command>
    </script>

    It happens that I need to obtain the name and type values from the XML but I'm getting the content with white spaces. Here is the code I'm trying to use:

    Code:
    void MySAX2Handler::startElement(const   XMLCh* const    uri,
                                const   XMLCh* const    localname,
                                const   XMLCh* const    qname,
                                const   Attributes&     attrs)
    {
        outStream.clear();
        char* message = XMLString::transcode(localname);
        std::cout << "I saw element: "<< message <<  std::endl;
        XMLString::release(&message);
    
    }
    
    void MySAX2Handler::fatalError(const SAXParseException& exception)
    {
        char* message = XMLString::transcode(exception.getMessage());
        std::cout << "Fatal Error: " << message
             << " at line: " << exception.getLineNumber()
             << std::endl;
    }
     
    void MySAX2Handler::characters(const XMLCh* const chars, const unsigned int length)
    {
        char* message = XMLString::transcode(chars);
        std::cout << "Characters: " << message << " Lenght: " << length << std::endl;
        if (XMLString::compareIString(chars,XMLUni::fgZeroLenString) != 0) {
          outStream << message;
        }
        XMLString::release(&message);
    }
    
    void MySAX2Handler::endElement(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname)
    {
          std::cout << "EndElement - OutStream: " << outStream.str() << std::endl;
    }
    But I'm still getting the outStream value from the endElement with white spaces.
    I would really appreciate if you can help me to solve this problem.

    Thank you.

    Nei
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    Not really familiar with SAX2.

    You should see the whitespace when you output the message here correct?

    [code=java]
    std::cout << "Characters : " << message << " Lenght: " << length << std::endl;
    [/code]
    You should be able to replace the whitespace like so:
    [code=java]
    message = message.replace All("\s+", " ");
    [/code]

    Note, this does not get rid of all whitespace, but adds in a single space where there used to be multiple spaces, newlines, tabs, etc..

    Comment

    Working...