【问题标题】:C# DataContractSerializer: convert .csv to .xml, no tabsC# DataContractSerializer:将 .csv 转换为 .xml,没有选项卡
【发布时间】:2015-10-16 16:41:26
【问题描述】:

想要将 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();

我的问题是,没有标签,这是为什么呢?

添加一些选项卡后,生成的代码似乎也正确! 我应该忽略它吗?这可以做到吗?已经四处搜索,但没有找到太多关于标签本身的信息。

【问题讨论】:

  • 你使用XmlDictionaryWriter而不是XmlWriter有什么原因吗? XmlWriter.Create 允许您传入具有 Indent 属性的设置,您可以将其设置为 true 以强制缩进。

标签: c# xml csv datacontractserializer


【解决方案1】:

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

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

【讨论】:

  • 像这样:writer.Settings.Indent = true; ?因为这会使对象未设置为引用错误,这很奇怪,因为我在后面添加了这一行:“var dcs = new DataCon...”
  • XmlDictionaryWriter 让您无法设置 Settings 属性,并且它不会在源代码中被覆盖,因此它默认为 null。您必须继承 XmlDictionaryWriter 才能覆盖设置。
  • 查看页面底部的示例代码——你需要新建一个XmlWriterSettings()并将其传递给Create。为此,您需要使用XmlWriter 而不是stackoverflow.com/questions/3604123/…
  • 我在您的指导下解决了这个问题,非常感谢 Paul!想投票赞成你的答案,但在我的情况下它并不完全正确,因此
猜你喜欢
  • 2016-12-12
  • 2021-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-20
  • 2013-10-04
  • 1970-01-01
相关资源
最近更新 更多