Xml文件未打开

本文关键字:文件 Xml | 更新日期: 2023-09-27 18:25:23

我正在开发C#应用程序,但在输入xml文件时遇到了一个问题。让我先展示一下代码:

Company comp = new Company();
comp.CompanyID = comboBox1.SelectedValue.ToString();
comp.CompanyName = comboBox1.Text;
comp.Serial = strEncryptedData;
comp.ListProduct = ll;
XmlDocument xDoc = new XmlDocument();
using (StringWriter stringWriter = new StringWriter())
{
    XmlSerializer serializer = new XmlSerializer(typeof(Company));
    serializer.Serialize(stringWriter, comp);
    xDoc.LoadXml(stringWriter.ToString());
}
string temp = xDoc.OuterXml;
MessageBox.Show(temp);
System.IO.StreamWriter sw = new System.IO.StreamWriter(@"c:'test.xml");
sw.WriteLine(temp);
sw.Flush();
sw.Close();

程序编写文件,但当我尝试以xml格式打开它时,我收到的是空白文档,里面什么都没有。当我在文本编辑器中打开它时,我收到了这个:

<?xml version="1.0" encoding="utf-16"?><CompanyXml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><CompanyName /><CompanyID>100</CompanyID><Serial>00000G2SB4BER9PSFJİ2GTVM2UC1VYEİ</Serial></CompanyXml>

这是我收到的正确数据,但不能作为xml打开。

如何格式化?还是我在写的时候做错了什么?

Xml文件未打开

只需从xml的第一行中删除此文本encoding="utf-16",即可打开xml。

问题似乎与编码有关,删除utf-16或更改为utf-8会更正它。

您可以尝试StreamWriter构造函数,它采用编码来查看是否使用正确的编码保存.xml。

例如:

StreamWriter sw = new StreamWriter(@"c:'test.xml", Encoding.UTF8);

然而,在你们指出utf格式问题后,我找到了其他方法来解决这个问题。

首先,我们创建一个扩展到StringWriter 的类

public class Utf8StringWriter : StringWriter
{
    public override Encoding Encoding
    {
        get { return Encoding.UTF8; }
    }
}

然后,我们通过修改StringWriter:将代码编辑为

Company comp = new Company();
comp.CompanyID = comboBox1.SelectedValue.ToString();
comp.CompanyName = comboBox1.Text;
comp.Serial = strEncryptedData;
comp.ListProduct = ll;
XmlDocument xDoc = new XmlDocument();
using (StringWriter stringWriter = new Utf8StringWriter())
{
    XmlSerializer serializer = new XmlSerializer(typeof(Company));
    serializer.Serialize(stringWriter, comp);
    StreamWriter sw = new StreamWriter(@"c:'text.xml");
    sw.WriteLine(stringWriter);
    sw.Flush();
    sw.Close();
}

问候。。。