0

我正在使用以下 XML 输出器基于 CSV 数据编写 xml 文件。

public override void Output(IRow input, IUnstructuredWriter output)
    {
        IColumn badColumn = input.Schema.FirstOrDefault(col => col.Type != typeof(string));
        if (badColumn != null)
        {
            throw new ArgumentException(string.Format("Column '{0}' must be of type 'string', not '{1}'", badColumn.Name, badColumn.Type.Name));
        }

        using (var writer = XmlWriter.Create(output.BaseStream, this.fragmentSettings))
        {
            writer.WriteStartElement(this.rowPath);
            foreach (IColumn col in input.Schema)
            {
                var value = input.Get<string>(col.Name);
                if (value != null)
                {
                    // Skip null values in order to distinguish them from empty strings
                    writer.WriteElementString(this.columnPaths[col.Name] ?? col.Name, value);
                }
            }
        }
    }

它工作得非常好,工作完全没有任何错误,但是,在预览和下载文件时,还有另一个额外的字符导致该 xml 文件被读取失败。我尝试使用片段级别和自动作为一致性级别。

我获得的样本输出是

在此处输入图像描述

并且 2 个标签之间的额外字符在读取文件时导致问题。

4

1 回答 1

0

我通过以下代码明确提供编码设置以及结束标签来解决了这个问题

private XmlWriterSettings fragmentSettings = new XmlWriterSettings
    {
        ConformanceLevel = ConformanceLevel.Auto,
        Encoding = Encoding.UTF8
    };

 public override void Output(IRow input, IUnstructuredWriter output)
    {
        IColumn badColumn = input.Schema.FirstOrDefault(col => col.Type != typeof(string));
        if (badColumn != null)
        {
            throw new ArgumentException(string.Format("Column '{0}' must be of type 'string', not '{1}'", badColumn.Name, badColumn.Type.Name));
        }
        using (var writer = XmlWriter.Create(output.BaseStream, this.fragmentSettings))
        {
            writer.WriteStartElement(this.rowPath);
            foreach (IColumn col in input.Schema)
            {
                var value = input.Get<string>(col.Name);
                if (value != null)
                {
                    // Skip null values in order to distinguish them from empty strings
                    writer.WriteElementString(this.columnPaths[col.Name] ?? col.Name, value);
                }
            }
            writer.WriteEndElement(); //explicit closing tag for stream
        }
    }

这会输出格式良好的 XML,可以使用任何 xml 阅读器轻松读取。

于 2016-04-06T05:00:53.143 回答