操作XML的XmlDeclaration

在数据库中使用openxml操作时,当xml字符串中含有中文时,结果sql对xml解析报错,xml内容如下:

<?xml version="1.0"?>
<order>
  <country>中国</country>
  <province>北京</province>
  <city>海淀区</city>
  <address>北京北京别急</address>
  <postalCode>100086</postalCode>
  <telephone>13811153770(62192343)</telephone>
  <email />
</order>

在把声明部分修改为<?xml version="1.0" encoding="gb2312" ?>后正常解析。

但由于xml的数据是从一个传入的字符串中加载来的,这个数据可能带头也可能会出现不带头的情况,在参考相关的资料后,通过如下的代码实现自己的需求。

XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(strXml);

if (xdoc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
{
    XmlDeclaration xmldecl 
= xdoc.FirstChild as XmlDeclaration;
    xmldecl.Encoding 
= "gb2312";
}

else
{
    XmlDeclaration xmldecl 
= xdoc.CreateXmlDeclaration("1.0""gb2312"null);
    xdoc.InsertBefore(xmldecl, xdoc.DocumentElement);
}
posted @ 2008-10-15 18:17  远去的河流  阅读(1707)  评论(1编辑  收藏  举报