Solve the problem that libXML2 does not support Chinese

xiaoxiao2021-03-06  43

When using libXML2 to process an XML file, the default load is encoded using UTF-8, so when modifying and saving as GB2312 encoding, you need to convert data to UTF-8 encoding, then modify and save!

Conversion uses iConV, the following is the conversion code

Char * Convertenc (Char * Encfrom, Char * Encto, Const Char * in) {Static Char BUFIN [1024], BUFOUT [1024], * SIN, * SOUT; INT MODE, LENIN, LENOUT, RET, NLINE; ICONV_T C_PT; IF ((c_pt = iconv_open) == (iconv_t) -1) {printf ("iconv_open false:% s ==>% s / n", encfrom, eNCTO); Return null;} iconv (c_pt , NULL, NULL, NULL, NULL); Lenin = Strlen (IN) 1; Lenout = 1024; SIN = (char *) in; sout = bufout; ret = iconv (c_pt, & sin, (size_t *) & lenin, & Sout , (size_t *) & lenout); if (RET == -1) {Return NULL;

}

Iconv_close (c_pt); return bufout;}

The following is an example

Test.xml

Test

Read code

INT main (void) {xmldocptr doc = null; XMLNodePtr Cur = NULL;

DOC = XMLPARSEFILE ("Test.xml"); cur = xmldocgetrootelEment (DOC); Printf ("% S / N", Convert ("UTF-8", "GB2312", (char *) XMLNodeGetContent (CUR)))) } Modify, save the code

TEST2.XML

john fleck June 2, 2002 I am also Example Keyword < / keyword> C Test this is the headline this is the body text. xmldocptr corresponddoc (char * docname, char * URI) {xmldocptr doc; xmlnodeptr news; xmlnodeptr news; xmlttrptr newattr

DOC = XmlParsefile (DOCNAME); if (DOC == NULL) {fprintf (stderr, "document not parse successfully. / n"); return (null);} cur = xmldocgetrootelement (DOC); if (cur == null) {FPRINTF (stderr, "empty document / n"); XMLFreedoc (DOC); return (null);} if (XmlStrcmp (Cur-> Name, (const Xmlchar *) "story")) {fprintf (stderr, "document Of the Wrong Type, Root Node! = Story "); XMLFreedoc (DOC); return (null); newode = XMLNewTextChild (cur, null, (xmlchar *)" Reference ", null); newattr = XMLNewProp (NewNode, Xmlchar *) "URI", (XMLCHAR *) URI); Return (DOC);

INT main (int Argc, char ** argv) {int options = 0; xmldocptr doc = null; char * OUTPUT = NULL; char * sznode = null; int RET = 0; XMLADDENCODINGALIAS ("UTF-8", "DVENC" ); xmlKeepBlanksDefault (0); defaultEntityLoader = xmlGetExternalEntityLoader (); xmlSetExternalEntityLoader (xmllintExternalEntityLoader); xmlLineNumbersDefault (1); szNode = Convert ( "gb2312", "utf-8", "test"); doc = parseDoc (argv [2] , SZNODE); RET = XmlsaveFormatfileEnc (Output? Output: "-", DOC, Argv [1], 1); if (RET <0) {fprintf (stderr, "failed save to% s / n", OUTPUT? OUTPUT : "-");} return 0;}

XMlout GB2312 TEST2.XML

result

john fleck June 2, 2002 I am also Example Keyword < / keyword> C Test this is the headline this is the body text.

转载请注明原文地址:https://www.9cbs.com/read-51211.html

New Post(0)