我正在开发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格式打开。
我该如何格式化?或者我在写作时做错了什么?
答案 0 :(得分:3)
只需从第一行xml中删除此文本 encoding =&#34; utf-16&#34; ,然后您将打开xml。
答案 1 :(得分:3)
问题似乎与编码有关,删除utf-16
或更改为utf-8
会对其进行更正。
您可以尝试使用编码的StreamWriter constructor来查看是否使用正确的编码保存.xml。
例如:
StreamWriter sw = new StreamWriter(@"c:\test.xml", Encoding.UTF8);
答案 2 :(得分: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();
}
...问候