0

我正在开发 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 格式打开。

我怎样才能格式化它?还是我在写的时候做错了什么?

4

3 回答 3

3

问题似乎与编码、删除utf-16或更改以utf-8纠正它有关。

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

例如:

StreamWriter sw = new StreamWriter(@"c:\test.xml", Encoding.UTF8);
于 2013-07-29T10:57:07.607 回答
3

只需从您的第一行 xml中删除此文本encoding="utf-16"然后您将打开 xml。

于 2013-07-29T10:51:23.250 回答
0

但是,在你们指出 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();
}

问候...

于 2013-07-29T11:19:39.593 回答