2010-12-16 19 views
9

que tienen algún XML en un string en la memoria exactamente como esta:¿Cómo se lee XML en una tabla de datos?

<symbols> 
    <symbol>EURCHF</symbol> 
    <symbol>EURGBP</symbol> 
    <symbol>EURJPY</symbol> 
    <symbol>EURUSD</symbol> 
</symbols> 

quiero leer esto en un DataTable. Lo estoy haciendo de esta manera:

DataTable dt = new DataTable(); 
dt.TableName = "symbols"; 
dt.Columns.Add("symbol"); 

if (!String.IsNullOrEmpty(symbols)) 
{ 
    dt.ReadXml(new StringReader(symbols)); 
} 

Sin embargo, cuando puedo comprobar el número de filas, el DataTable termina por tener cero filas. ¿Qué estoy haciendo mal?

+0

duplicado posible de [Código para la lectura de un archivo XML en un DataTable] (http://stackoverflow.com/questions/9781796/code-for- reading-an-xml-file-into-a-datatable) –

Respuesta

14

A partir de aquí: http://www.dreamincode.net/code/snippet3186.htm

// <summary> 
/// method for reading an XML file into a DataTable 
/// </summary> 
/// <param name="file">name (and path) of the XML file</param> 
/// <returns></returns> 
public DataTable ReadXML(string file) 
{ 
    //create the DataTable that will hold the data 
    DataTable table = new DataTable("XmlData"); 
    try 
    { 
     //open the file using a Stream 
     using(Stream stream = new FileStream(file, FileMode.Open, FileAccess.Read)) 
     { 
      //create the table with the appropriate column names 
      table.Columns.Add("Name", typeof(string)); 
      table.Columns.Add("Power", typeof(int)); 
      table.Columns.Add("Location", typeof(string)); 

      //use ReadXml to read the XML stream 
      table.ReadXml(stream); 

      //return the results 
      return table; 
     }     
    } 
    catch (Exception ex) 
    { 
     return table; 
    } 
} 

Es posible que desee echar un vistazo a DataTable.ReadXml método.

EDITAR: Si tiene un objeto xml en la memoria, puede usar el método ReadXml directamente. DataTable.ReadXml(MemoryStream Object);

EDIT 2: Hice la exportación. Se requiere el siguiente esquema XML:

<?xml version="1.0" standalone="yes"?> 
<DocumentElement> 
    <symbols> 
    <symbol>EURCHF</symbol> 
    </symbols> 
    <symbols> 
    <symbol>EURGBP</symbol> 
    </symbols> 
    <symbols> 
    <symbol>EURJPY</symbol> 
    </symbols> 
</DocumentElement> 
+0

Eso es lo que estoy haciendo. Mi pregunta es ¿por qué mi mesa tiene cero filas? ¿Qué pasa con mi código? –

+3

Probablemente sea un problema de esquema. Intente crear una tabla de datos similar y llame a WriteXML. Luego verifique lo que está escrito y compare con su xml. Esto debería aclarar la duda de por qué datatable está vacía. –

+0

Gracias, eso me ayudó a resolverlo. Lo estaba escribiendo de una manera diferente y ahora estoy usando 'DataTable.WriteXml' y funciona muy bien. –

2

De esta manera:

Dim strXmlString As String = "<tables><row><table_name>Table1</table_name><record_key>1</record_key></row>" 
strXmlString += "<row><table_name>Table2</table_name><record_key>2</record_key></row></tables>" 
Dim srXMLtext As System.IO.StringReader = New System.IO.StringReader(strXmlString) 

Dim dt As New DataTable 
dt.ReadXml(srXMLtext) 
+1

Nota: aún deberá agregar explícitamente el esquema a DataTable (que falta en el ejemplo anterior). –

-2

Uso conjunto de datos en lugar de la tabla de datos

0

Otra forma:

public DataTable ReadXML(string yourPath) 
 
     { 
 
      DataTable table = new DataTable("Item"); 
 
      try 
 
      { 
 
       DataSet lstNode = new DataSet(); 
 
       lstNode.ReadXml(yourPath); 
 
       table = lstNode.Tables["Item"]; 
 
       return table; 
 
      } 
 
      catch (Exception ex) 
 
      { 
 
       return table; 
 
      } 
 
     }

Y aquí es formato XML:

<?xml version="1.0" encoding="utf-8" ?> 
 
<db> 
 
    <Item> 
 
    <Id>222</Id> 
 
    <OldCode>ZA</OldCode> 
 
    <NewCode>ZAF</NewCode> 
 
    <Name>Africa (South)</Name> 
 
    </Item> 
 
</db>

Cuestiones relacionadas