Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
Questo articolo fornisce un esempio su come usare C# e Visual Basic per generare un file di testo con valori delimitati da virgole (CSV) da un file XML.
Esempio: generare un file CSV da un documento XML
In questo esempio viene generato un file CSV da un documento XML File XML campione: clienti e ordini.
La versione C# usa la sintassi di metodo e l'operatore Aggregate per generare il file in un'espressione singola. Per altre informazioni, vedere Sintassi di query e sintassi di metodi in LINQ (C#).
Nella versione Visual Basic viene usato codice procedurale per aggregare la raccolta di stringhe in un'unica stringa.
XElement custOrd = XElement.Load("CustomersOrders.xml");
string csv =
(from el in custOrd.Element("Customers").Elements("Customer")
select
String.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}{10}",
(string)el.Attribute("CustomerID"),
(string)el.Element("CompanyName"),
(string)el.Element("ContactName"),
(string)el.Element("ContactTitle"),
(string)el.Element("Phone"),
(string)el.Element("FullAddress").Element("Address"),
(string)el.Element("FullAddress").Element("City"),
(string)el.Element("FullAddress").Element("Region"),
(string)el.Element("FullAddress").Element("PostalCode"),
(string)el.Element("FullAddress").Element("Country"),
Environment.NewLine
)
)
.Aggregate(
new StringBuilder(),
(sb, s) => sb.Append(s),
sb => sb.ToString()
);
Console.WriteLine(csv);
Dim custOrd As XElement = XElement.Load("CustomersOrders.xml")
Dim strCollection As IEnumerable(Of String) = _
From el In custOrd.<Customers>.<Customer> _
Select _
String.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}{10}", _
el.@CustomerID, _
el.<CompanyName>.Value, _
el.<ContactName>.Value, _
el.<ContactTitle>.Value, _
el.<Phone>.Value, _
el.<FullAddress>.<Address>.Value, _
el.<FullAddress>.<City>.Value, _
el.<FullAddress>.<Region>.Value, _
el.<FullAddress>.<PostalCode>.Value, _
el.<FullAddress>.<Country>.Value, _
Environment.NewLine _
)
Dim sb As StringBuilder = New StringBuilder()
For Each str As String In strCollection
sb.Append(str)
Next
Console.WriteLine(sb.ToString())
Nell'esempio viene prodotto l'output seguente:
GREAL,Great Lakes Food Market,Howard Snyder,Marketing Manager,(503) 555-7555,2732 Baker Blvd.,Eugene,OR,97403,USA
HUNGC,Hungry Coyote Import Store,Yoshi Latimer,Sales Representative,(503) 555-6874,City Center Plaza 516 Main St.,Elgin,OR,97827,USA
LAZYK,Lazy K Kountry Store,John Steel,Marketing Manager,(509) 555-7969,12 Orchestra Terrace,Walla Walla,WA,99362,USA
LETSS,Let's Stop N Shop,Jaime Yorres,Owner,(415) 555-5938,87 Polk St. Suite 5,San Francisco,CA,94117,USA