[英]StyleCop happy creation of Xml using XDocument / XElement / XAttribute
[英]csv to xml not adding xElement if XAttribute = “”
我已經從這樣的csv文件創建了一個xml文件
private void button2_Click(object sender, EventArgs e)
{
String[] FileContent = File.ReadAllLines(csvPathFile);
String XMLNS = "";
int idCountProduct = 1;
XElement Inv = new XElement("data",
from items in FileContent
let fields = items.Split(';')
select new XElement("category",
new XAttribute("idCategory", fields[0]),
new XAttribute("CategoryName", fields[1]),
new XElement("products",
new XElement("product",
new XAttribute("IdProduct", idCountProduct++),
new XAttribute("Rif", fields[0]),
new XAttribute("ProductName", fields[2]),
new XElement("products",
new XElement("product",
new XAttribute("IdProduct", idCountProduct++),
new XAttribute("Rif", fields[0]),
new XAttribute("ProductName", fields[3]),
new XElement("products",
new XElement("product",
new XAttribute("IdProduct", idCountProduct++),
new XAttribute("Rif", fields[0]),
new XAttribute("ProductName", fields[4]));
File.WriteAllText(xmlPathFile, XMLNS + Inv.ToString());
}
這是我的csv文件
1;Beverages;Lemon Juice;;Orange Juice
這是我要創建的xml文件
<data>
<category idCategory="1" CategoryName= "Beverages">
<products>
<product IdProduct="1" Rif="1" ProductName= "Lemon Juice" />
<product IdProduct="2" Rif="1" ProductName= "Orange Juice" />
<products/>
<category/>
</data>
這是我獲得的xml文件
<data>
<categories>
<category idCategory="1" CategoryName= "Beverages">
<products>
<product IdProduct="1" Rif="1" ProductName= "Lemon Juice" />
<product IdProduct="2" Rif="1" ProductName= "" />
<product IdProduct="3" Rif="1" ProductName= "Orange Juice" />
<products/>
<category/>
<categories/>
</data>
如果未分配ProductName,如何避免添加產品?
將過濾器添加到LINQ查詢中以過濾出空產品:
where !String.IsNullOrEmpty(fields[4])
在此之后:
let fields = items.Split(';')
無論如何,如果您的條件如此簡單,您甚至不需要它,並且可以從Split指令本身中過濾出條目:
let fields = items.Split(';', StringSplitOptions.RemoveEmptyEntries)
編輯您的代碼是相當固定的,因此...確定要使用LINQ和LINQ-to-XML嗎? 我想無論如何它都會更具可讀性...編寫如下:
XElement data = new XElement("data");
XDocument document = new XDocument(data);
int counter = 0;
foreach (string entry in File.ReadAllLines(csvPath))
{
string[] fields = entry.Split(new char[] { ';' },
StringSplitOptions.RemoveEmptyEntries);
XElement category = new XElement("category",
new XAttribute("idCategory", fields[0]),
new XAttribute("CategoryName", fields[1]));
data.Add(category);
XElement products = new XElement("products");
category.Add(products);
for (int i = 2; i < fields.Length; ++i)
{
products.Add(new XElement("product",
new XAttribute("IdProduct", counter++),
new XAttribute("Rif", fields[0]),
new XAttribute("ProductName", fields[i])));
}
}
document.Save(xmlPath);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.