0
我已經創建一個CSV文件的XML文件是這樣CSV到XML中是增加的XElement如果XAttribute = 「」
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未分配,我該如何避免添加產品?
謝謝,但這樣一來,連我的類別,則不能打印到XML。即使沒有關聯產品,我也喜歡擁有類別。 – Barbara 2012-04-19 10:28:25
如果您的類別是CSV中的第一列,那麼如果您使用StringSplitOptions.RemoveEmptyEntries它不會被分割出來。 – 2012-04-19 10:39:07
我在let子句後使用where條件。我需要一個只符合產品的條件。有任何想法嗎? – Barbara 2012-04-19 10:47:24