2011-01-14 16 views
5

Ho letto oltre i vecchi thread qui e le pagine che ho trovato su Google, e posso dire onestamente che questo mi ha confuso completamente. Sembra che ci siano circa 1000 modi per analizzare stringhe XML usando C# .NET e non so quale usare. Sembra che tutti gli esempi che trovo si basino su uno specifico nodo root con nome e così via.C#. Parsing XML Strings

Quello che ho è ...

<whmcsapi version="4.1.2"> 
<action>getstaffonline</action> 
<result>success</result> 
<totalresults>1</totalresults> 
<staffonline> 
    <staff> 
    <adminusername>Admin</adminusername> 
    <logintime>2010-03-03 18:29:12</logintime> 
    <ipaddress>127.0.0.1</ipaddress> 
    <lastvisit>2010-03-03 18:30:43</lastvisit> 
    </staff> 
</staffonline> 
</whmcsapi> 

Ho solo bisogno di ottenere i valori per le informazioni e ogni membro del personale (racchiuso tra i tag). Qualcuno può dirmi quale sarebbe il modo migliore per farlo e forse un piccolo esempio?

Grazie!

+0

Suggerimento: il nodo principale è denominato 'whmcsapi' –

+1

possibile duplicato di [Come leggere e analizzare un file XML in C#?] (Http://stackoverflow.com/questions/642293/how-do- i-read-and-parse-an-xml-file-in-c) –

+2

Il problema è che non sto analizzando un file, ho i dati XML in una stringa. Tutto quello che trovo è su come analizzare un file. –

risposta

12
var staff = XDocument.Parse(myXml) 
    .Descendants("staff") 
    .Select(n => new { 
         adminusername = n.Element("adminusername").Value, 
         ... 
        }); 
3

più comunemente usato è Linq to XML in questi giorni, si integra analisi XML in LINQ per una bella, succinta ed espressivo sintassi:

XDocument xmlDoc = XDocument.Load(@"testData.xml"); 
var staffMembers = xmlDoc.Descendants("staff") 
         .Select(staff => new { Name = staff.Element("adminusername").Value, 
               LoginTime = staff.Element("logintime").Value, 
               IpAddress = staff.Element("ipaddress").Value, 
               LastVisit = staff.Element("lastvisit").Value, 
              }).ToList(); 
+0

Non capisco perché questo stia avendo problemi. Non importa come lo provo, ottengo "caratteri illegali nel percorso". Posso non caricarlo in questo modo da una stringa? http://www.ampaste.net/m3651f133 –

+1

per caricare da una stringa usare 'XDocument.Parse (myString)' – BrokenGlass

+0

Ah grazie, l'ho appena notato dall'altro commento. Capisci perché questo non avrebbe funzionato? Le due parti nella parte inferiore del metodo non aggiornano la listbox e l'etichetta, sebbene l'XML sia stato estratto correttamente. Quindi presumo sia un problema di analisi. http://www.ampaste.net/m61f246e1 –

0
XDocument doc = XDocument.Load("staff.xml"); 

var query = from r in doc.Descendants("staff") 
      select new 
        { 
         Adminusername = r.Element("adminusername").Value, 
         LoginTime = r.Element("logintime").Value, 
         IpAddress = r.Element("ipaddress").Value, 
         LastVisit = r.Element("lastvisit").Value 
        }; 
-3

Ecco una funzione che uso che funziona perfettamente analizzare i file xml. Ho incluso una classe 'delimitatore' che è possibile utilizzare per memorizzare delimitatori XML come

<startTag></endTag> 

Veramente facile da usare, e funziona come un fascino ... fatemi sapere se avete domande

utilizzare la funzione come questa:

XmlDataManager.List<XmlManager.Delimeter> delimeters = new List<XmlManager.Delimeter>("<result>","</result>"); 
int[] splitIndexArray = { 1 }; // Tells the function where to split in case where the same value occurs multiple times in a line... usually 1 need an entry for each value 
String testValue = ""; 
List<String> values = new List<String> {testValue} 
XmlDataManager.ReadValues(delimeters, values, `<xmlFileNameHere>,` splitIndexArray); 

Qui è la classe:

public class XmlDataManager 
{ 
    const String XML_FILE_WRITE_FAIL = "Could not write to xml file"; 
    const String XML_FILE_READ_FAIL = "Could not read from xml file"; 
    const String XML_FILE_WRITE_BUILDER_FAIL = "Could not write values to string"; 


    /// <summary> 
    /// 
    /// </summary> 
    public struct Delimeter 
    { 
     internal String StartDelimeter { get { return _startDelimeter; } } 
     internal String EndDelimeter { get { return _endDelimeter; } } 
     private readonly String _startDelimeter; 
     private readonly String _endDelimeter; 

     public Delimeter(String startDelimeter, String endDelimeter) 
     { 
      _startDelimeter = startDelimeter; 
      _endDelimeter = endDelimeter; 
     } 

     public Delimeter(String startDelimeter) 
     { 
      _startDelimeter = startDelimeter; 
      _endDelimeter = String.Empty; 
     } 
    } 


    public static void ReadValuesLineByLine( List<Delimeter> elementDelimeters, 
               List<String> values, 
               String fileName, 
               int[] splitIndexes) 
    { 
     try 
     { 
      using (StreamReader sr = new StreamReader(fileName)) 
      { 
       String line = sr.ReadLine(); 
       while (!sr.EndOfStream) 
       { 
        for (int i = 0; i <= values.Count-1; i++) 
        { 
         if (line.Contains(elementDelimeters[i].StartDelimeter)) 
         { 
          String[] delimeters = { elementDelimeters[i].StartDelimeter, elementDelimeters[i].EndDelimeter }; 
          String[] elements = line.Split(delimeters, StringSplitOptions.None); 
          values[i] = elements[splitIndexes[i]]; 
         } 
        } 
        line = sr.ReadLine(); 
       } 
      } 
     } 
     catch(Exception ex) 
     { 
      throw new Exception(XML_FILE_READ_FAIL, ex); 
     } 
    } 
} 

Peter

+1

c'è un motivo per cui hai inventato la tua classe di analisi XML quando c'è una funzionalità perfettamente pronta per farlo? Sono un po 'scioccato, devo dire. – BrokenGlass

+0

Seriamente, perché lo faresti a te stesso? – Jordan