下面是我的示例CSV
name setup_fee_in_cents
Platinum {'INR': 18995, 'EUR': 0, 'USD': 4495, 'NZD': 35995}
现在,当我通过C#将上述CSV转换为XML时,它将呈现如下。
<?xml version="1.0" encoding="UTF-8"?>
<row>
<name>Platinum</name>
<setup_fee_in_cents>{'GBP': 18995, 'EUR': 0, 'AUD': 33995, 'USD': 4495, 'CAD': 26495, 'NZD': 35995}</setup_fee_in_cents>
</row>
</root>
这是C#函数的外观
public static (string data, bool flag) ToXml(string filePath, string elementName)
{
try
{
string xml = string.Empty;
using (MemoryStream result = new MemoryStream())
{
using (CsvReader reader = new CsvReader(filePath))
{
XmlTextWriter writer = new XmlTextWriter(result, Encoding.Default)
{
Formatting = System.Xml.Formatting.Indented,
IndentChar = '\t',
Indentation = 4
};
writer.WriteStartDocument();
writer.WriteStartElement(elementName + "s");
reader.ReadHeaders();
while (reader.ReadRecord())
{
writer.WriteStartElement(elementName);
for (int i = 0; i < reader.ColumnCount; i++)
{
var key = reader.GetHeader(i).ToLower()[0] + reader.GetHeader(i).Substring(1);
var value = reader[i];
if(key == "setup_fee_in_cents")
{
var xmlNode = JsonConvert.DeserializeXmlNode(value, key);
//#LINE OF ERROR
}
else
{
writer.WriteElementString(key, value);
}
}
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
using (StreamReader resultReader = new StreamReader(new MemoryStream(result.ToArray())))
{
xml = resultReader.ReadToEnd();
}
}
}
return (xml, true);
}
catch (Exception ex)
{
return (ex.Message ?? ex.InnerException.Message, false);
}
}
在#Line Of Error,我尝试了多种选择
Writer.WriteNode
write.WriteString
但是所有人都在翻译像编码的特殊符号“ <”。
我检查了以下链接
如何将CSV中的JSON转换为嵌入XML文档?