2015-10-16 50 views
0

想CSV转换为XML,使用此代码:C#的DataContractSerializer:转换.csv格式.XML,无标签

  // test person 
     var person = new Person("Jim", "TestJob", 1000); 
     var fileStream = new FileStream("sample.xml", FileMode.Create); 
     var writer = XmlDictionaryWriter.CreateTextWriter(fileStream); 
     var dcs = new DataContractSerializer(typeof(Person)); 

     // Use the writer to start a document. 
     writer.WriteStartDocument(true); 

     // Use the writer to write the root element. 
     writer.WriteStartElement("Company"); 

     // Use the writer to write an element. 
     writer.WriteElementString("Name", "Microsoft"); 

     // Use the serializer to write the start, 
     // content, and end data. 
     dcs.WriteObject(writer, person); 

     // Use the writer to write the end element and 
     // the end of the document 
     writer.WriteEndElement(); 
     writer.WriteEndDocument(); 

     // Close and release the writer resources. 
     writer.Flush(); 
     fileStream.Flush(); 
     fileStream.Close(); 

问题我有,没有标签,这是为什么? enter image description here

添加一些标签后,生成的代码似乎也是正确的! enter image description here 我应该忽略它吗?这可以做到吗?已经搜索过,但没有太多发现关于标签本身。

+0

有没有你正在使用'XmlDictionaryWriter'而不是'XmlWriter'理由吗? 'XmlWriter.Create'允许您传入具有缩进属性的设置,您将其设置为true来强制缩进。 –

回答

0

XmlDictionaryWriter有一个Settings财产,其中一个设置属性是Indent

https://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings(v=vs.110).aspx

+0

像这样:writer.Settings.Indent = true; ?因为这给对象没有设置参考错误,这是奇怪的,因为我在下面添加了这一行:“var dcs = new DataCon ...” –

+0

'XmlDictionaryWriter'无法设置'Settings'属性,它不是在源代码中被覆盖,所以它默认为null。你将不得不继承'XmlDictionaryWriter'来覆盖设置。 –

+1

查看页面底部的示例代码 - 您需要创建一个新的'XmlWriterSettings()'并将其传递到'Create'。要做到这一点,你需要使用'XmlWriter'来代替http://stackoverflow.com/questions/3604123/xmlwriter-vs-xmldictionarywriter –