2010-07-19 16 views
5

mi passerà il file xml in questo modo:Come leggere file XML usando System.IO.Stream con LINQ

File1.PostedFile.InputStream 

//reading xml file..... 
public static void readXMLOutput(Stream stream) 
{ 

    System.Xml.Linq.XDocument xml = System.Xml.Linq.XDocument.Load(stream); 

    var query = from p in xml.Element("ste").Element("Application") 
       //where (int)p.Element("Id") == 1 
       select Page; 

    foreach (var record in query) 
    { 
     Response.Write("dfe") + record.Element("dfe").Value; 
    } 

errore:

Error 1 The best overloaded method match for 'System.Xml.Linq.XDocument.Load(string)' has some invalid arguments

cannot convert from 'System.IO.Stream' to 'string'

risposta

12

Si sta utilizzando .NET 3.5 da qualsiasi opportunità? XDocument.Load(Stream) apparentemente è arrivato solo in .NET 4.

È possibile utilizzare the overload which takes an XmlReader (che è supportato in 3.5).

EDIT: Codice di esempio:

static XDocument LoadFromStream(Stream stream) 
{ 
    using (XmlReader reader = XmlReader.Create(stream)) 
    { 
     return XDocument.Load(reader);  
    } 
} 
+0

sì, sto usando 3.5 framework. quale dovrebbe essere l'alternativa ad esso? –

+0

puoi mostrarmi alcune righe di esempio Stream usando xmlReader? –

+0

@teki: modificato per fornire un metodo che è possibile utilizzare. –

3

Il metodo XDocument.Load(Stream) è nuova in .NET 4. Per le versioni precedenti del quadro, è necessario leggere il flusso prima e passarlo in forma di stringa:

public static void readXMLOutput(Stream stream){ 
    string streamContents; 
    using(var sr = new StreamReader(stream)){ 
     streamContents = sr.ReadToEnd(); 
    } 

    var document = XDocument.Parse(streamContents); 
} 
+0

errore di ricezione quando si tenta di caricare lo streamContents e l'errore è: "Caratteri non validi nel percorso.", Il mio xml è praticamente niente personaggi speciali non speciali. –

+1

XDocument.Load accetta un nome file, non l'XML stesso. Tu * potresti * usare invece XDocument.Parse - ma il codice in questa risposta assume attualmente UTF-8 ... sarebbe più robusto usare XmlReader.Create IMO. –

+0

Sì, corretto. Grazie – LorenzCK