C# 读取 CSV 字段,包括要处理的字段中的空格 XML

C# Reading CSV fields including whitespaces in the fields to process XML

我正在尝试使用 C# 读取 CSV 文件并根据其中的值处理 XML。如果 CSV 中的字段没有空格,即 age,我的代码工作正常,但当字段类似于 First Name 时,我的代码会失败。如何使用 C# 读取整个字符串?

我在 CSV 文件中只有 2 列:

Customer,id
Customer,age
Customer,sex
Customer,First Name     
Address,Street
Address,Street Id      
Custom,Applicant Last Name
Custom,Social Security -CB

代码如下:

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace DataScrub_Test
{
    class Program
    {
         static void Main(string[] args)
        {
            String[] lines =  System.IO.File.ReadAllLines(@"C:\Users\Jason\Desktop\Input\test1.csv");
            List<string> Parent = new List<string>();
            List<string> Node = new List<string>();
            foreach (string line in lines)
            {
                string[] values = line.Split(',');
                Parent.Add(values[0]);
                Node.Add(values[1]);
                Console.WriteLine(Parent[0]);
            }

            var doc = XDocument.Parse(System.IO.File.ReadAllText("C:\Users\Jason\Desktop\Input\2015\09\03\filename.xml"));
            for (int i = 0; i < Parent.Count; i++)
            {
                foreach (var p in doc.Descendants(Parent[i]))
                {
                    var nodevar = p.Attribute(Node[i]);
                    if (nodevar != null)
                    {
                        nodevar.Remove();
                    }

                }
                var result = doc.Descendants("CustomField").Where(x => x.Attribute("text").Value == Node[i]);
                    if (result != null)
                    {
                        result.Remove();
                    }
            }
doc.Save("C:\Users\Jason\Desktop\Input\2015\09\03\filename.xml");
        }
    }

}

我得到的异常是:

The ' ' character, hexadecimal value 0x20, cannot be included in a name.

异常出现在这一行:var nodevar = p.Attribute(Node[i]);

您可以使用这种方式 space 读取整个字符串

string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Jason\Desktop\Input\test1.csv");
List<string> Parent = new List<string>();
List<string> Node = new List<string>();

foreach (string line in lines)
{
   string[] values = line.Split(',');
   Parent.Add(values[0]);
   Node.Add(values[1]);
   Console.WriteLine(Parent[0]);
}

始终使用解析器,否则如果任何文本包含 , 个字符,您就会抓狂。

TextFieldParser parser = new TextFieldParser(new StringReader(line));
parser.HasFieldsEnclosedInQuotes = true;
parser.SetDelimiters(",");

while (!parser.EndOfData)
{
    var values = parser.ReadFields();

    Parent.Add(values[0]);
    Node.Add(values[1]);

最后一个问题更新

您需要规范化该名称。异常告诉您属性不能包含白色 space ' ' 字符(在 First Name 中找到的字符)。

最常用的方法是规范化白色 spaces 是将它们替换为下划线字符 '_'.

var nodevar = p.Attribute(Node[i].Replace(" ", "_"));