简体   繁体   中英

how to trim the whitespace from headers when converting csv to xml

Currently I am using this code.

private void btnTurnXml_Click(object sender, EventArgs e)
    {
        var lines = File.ReadAllLines(@"C:\StockFile\stocklist.csv");
        string[] headers = lines[0].Split(',').Select(x => x.Trim('\"')).ToArray();

        var xml = new XElement("TopElement",
           lines.Where((line, index) => index > 0).Select(line => new XElement("Item",
              line.Split(',').Select((column, index) => new XElement(headers[index], column)))));

        // Saves to same location as the csv as xml
        xml.Save(@"C:\StockFile\CsvXmlout.xml");
    }

and I am receiving "An unhandled exception of type

'System.Xml.XmlException' occurred in System.Xml.dll

Additional information: The ' ' character, hexadecimal value 0x20, cannot be included in a name."

I think it because for the whitespace in the CSV's headers eg Monkey Soup. but i can't seem to trim it perhaps I'm doing something wrong would be great if you could point me in right direction.

By default, .Trim() will remove all of the leading and trailing whitespace in a string. However, .Trim(params char[] c) will only remove leading and trailing characters that are contained in c from the string.

In your usage, it appears that only the character " (ASCII Code 34 ) will be trimmed from each of the headers, leaving all of the leading and trailing whitespace. Adding spaces and tabs to your list of trim characters would solve your whitespace issue:

x.Trim('\"', ' ', '\t')

Additionally , it is important to note that whitespace characters are not allowed in XML tag names at all . Therefore, it is probably in your best interest to simply remove all of the whitespace from each header:

// Feel free to use a Regex or something if
// you think it produces cleaner code.
x.Trim('\"').Replace(" ", "").Replace("\t", "");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM