zoukankan      html  css  js  c++  java
  • delphi NativeXml的中文支持 乱码

    一般XML的编码格式设置成UTF8比较通用,下面演示使用UTF8编码方式存储和处理包含中文的XML字符串(文件)。1.设置启用内置的widestring支持

    NativeXml内部使用ANSI string和UTF8编码的string两种字符串类型。如果要让NativeXml能够解析widestring字符串的话,直接将TNativeXml的Utf8Encoded属性设置为True。如下:

    FXmlDoc:= TNativeXml.Create;
    FXmlDoc.Utf8Encoded:= True;

    这样NativeXml内部会自动对Widestring和utf8做转换。此处需要注意的是,如果执行FXmlDoc.Clear
    以后再次加载Xml字符串的话,需要重新设置Utf8Encoded属性为True,加载文件或流之前同样需要设置。


    2.加载widestring字符串

    mmoText 是Tnt Unicode控件Text值为Widestring类型,这里要手动将Widestring转换成utf8编码的string,然后调用 ReadFromString方法加载。sdUnicodeToUtf8转换函数NativeXml.pas内置。如下:

    FXmlDoc.ReadFromString(sdUnicodeToUtf8(mmoText.Text));


    3.使用ValueAsWidestring、FromWidestring

    通过使用Node.ValueAsWidestring可以读取、写入widestring类型的节点值。节点其他属性可以使用FromWidestring方法转换widestring类型到utf8 string。如下:
    procedure AddNode(ADoc: TXmlDocument; AName, AValue: widestring);
    begin
    with ADoc.Root do
    with NodeNew(FromWidestring(AName)) do
    ValueAsWidestring := AValue;
    end;

    4.保存到文件

    将包含中文的XML文档保存到文件,最重要一点是设置ExternalEncoding属性。ExternalEncoding详细设置参考Help。这里以utf8为例:

    FXmlDoc.VersionString:= '1.0′;
    FXmlDoc.EncodingString:= 'UTF-8′;
    FXmlDoc.ExternalEncoding:= seUTF8;
    FXmlDoc.SaveToFile(’C:Test.xml’);

    如果是非中文操作系统,不能直接使用SaveToFile保存文件到含有中文的路径,解决方法是先创建一个TTntFileStream文件流然后使用SaveToStream保存。 

    var
    lFS: TTntFileStream;
    begin
    if dlgSave.Execute then
    begin FXmlDoc.VersionString:= '1.0';
    FXmlDoc.EncodingString:= 'UTF-8';
    FXmlDoc.ExternalEncoding:= seUTF8;
    lFS:= TTntFileStream.Create(dlgSave.FileName, fmCreate or fmShareDenyNone);
    try
    FXmlDoc.SaveToStream(lFS);
    finally
    lFS.Free;
    end;
    end;
    end;

    5.如果xml是utf-8 格式的  

    NativeXml.WriteToString是乱码,解决方法如下:

    Utf8ToAnsi(NativeXml.WriteToString)

  • 相关阅读:
    SPOJ GSS4 Can you answer these queries IV ——树状数组 并查集
    SPOJ GSS3 Can you answer these queries III ——线段树
    SPOJ GSS2 Can you answer these queries II ——线段树
    SPOJ GSS1 Can you answer these queries I ——线段树
    BZOJ 2178 圆的面积并 ——Simpson积分
    SPOJ CIRU The area of the union of circles ——Simpson积分
    HDU 1724 Ellipse ——Simpson积分
    HDU 1071 The area ——微积分
    HDU 4609 3-idiots ——FFT
    BZOJ 2194 快速傅立叶之二 ——FFT
  • 原文地址:https://www.cnblogs.com/zhangzhifeng/p/3262652.html
Copyright © 2011-2022 走看看