Re: [xml] Special chars in XML



libxml2 should take care of special chars of itself.
Quick and dirty Perl example:
----------- snip -----------
use strict;
use XML::LibXML;
my $xml = XML::LibXML::Document->new('1.0', 'utf-8');
my $root = XML::LibXML::Element->new('test');    
$xml->setDocumentElement($root);
my $item = XML::LibXML::Element->new('item1');
$root->appendChild($item);
$item->appendText('This a string with < & > chrs, watch me!');
print $xml->toString(),"\n";
----------- snip -----------

The result of the above code should be:
<?xml version="1.0" encoding="utf-8"?>
<test><item1>This a string with &lt; &amp; &gt; chrs, watch me!</item1></test>

Otherwise, you should consider using the libxml2's xmlEncodeEntitiesReentrant function (http://xmlsoft.org/html/libxml-entities.html#xmlEncodeEntitiesReentrant).

In any case it doesn't mean you can put binary data in a text node,
you should sanitize the data first or use some encoding.

Hope this could help.
Regards
R.Scussat
DSPLABS Srl
dsplabs dsplabs net
PGP Key ID: 0x618E24FE


samaram s wrote:
But i am using libxml2 C library API's for writing string data...
I dont know what strings i will be getting in my application...It is dynamic.
So i was wondering is there any API which could help me out to take care of special characters.

Thanks,
Sam

On Wed, Dec 29, 2010 at 5:56 PM, Liam R E Quin <liam holoweb net> wrote:
On Wed, 2010-12-29 at 17:35 -0500, samaram s wrote:

> I am working with libxml2 library for one of my application.
> But in my data there are few strings which has some special characters  like
> ('&' , < , >) etc

You need to escape some of these characters in your data.

For & use &amp; instead.

For < and > use &lt; and &gt;

Inside attribute values, for " and ' use &quot; and &apos;
(you can quote them in other places too but it is not necessary)

For example,
   <activity whose="Susan's">R & D budget < 30000</activity>
might be quoted as
   <activity whose="Susan's">R &amp; D budget ^lt; 30000</activity>

You only need to quote " in attribute values if " was used for the
quotes and the same with ', like this
   <activity whose='Susan&apos;s'>....


You do not need to use a DTD for any of this.

Liam

--
Liam Quin - XML Activity Lead, W3C, http://www.w3.org/People/Quin/
Pictures from old books: http://fromoldbooks.org/




_______________________________________________ xml mailing list, project page http://xmlsoft.org/ xml gnome org http://mail.gnome.org/mailman/listinfo/xml


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]