2016-05-24 10 views
2

Ich suche ein paar Tage, wie ich meine XML-Datei parsen kann. Also mein Problem Ich möchte alle Schlüssel-Werte des Root-Elements wiederherstellen.Wie bekomme ich alle Schlüssel-Werte des Wurzelelements mit C#?

Exemple der Datei:

<?xml version="1.0" ?> 
<!DOCTYPE ....... SYSTEM "....................."> 
<coverage x="y1" x2="y2" x3="y3" x4="y4"> 
    <sources> 
     <source>.............</source> 
    </sources> 
    ..... 
<\coverage> 

Hier finden möchte ich all den Wert von "coverage" Wiederherstellen: x1 und seinen Wert, x2 und seinen Wert, x3 und sein Wert x3 ... I habe bereits versucht, "XmlReader" mit all dem Tutorial zu verwenden, das ich finden konnte, aber es funktioniert immer noch nicht. Alle Tutorials, die ich ausprobiert habe, stellen einen Wert in einem bestimmten Knoten (Tag) wieder her, aber nie alle Werte des Wurzelelements.

Vielleicht gibt es bereits ein Tutorial mit demselben Problem, aber ich habe ihn nicht gefunden.

Vielen Dank im Voraus für Ihre Hilfe.

+0

Betrachten Sie die rekursive Methode auf der folgenden Webseite: http://StackOverflow.com/Questions/28976601/Recursion-Parsing-xml-File-with-Attributes-into-treeview-c-sharp – jdweng

Antwort

1

Sie könnten XElement verwenden und dies tun.

XElement element = XElement.Parse(input); 

var results = element.Attributes() 
        .Select(x=> 
          new 
          { 
           Key = x.Name, 
           Value = (string)x.Value 
          }); 

Ausgabe

{ Key = x, Value = y1 } 
{ Key = x2, Value = y2 } 
{ Key = x3, Value = y3 } 
{ Key = x4, Value = y4 } 

prüfen diese Demo

0
 //Use System.Xml namespace 
     //Load the XML into an XmlDocument object 
     XmlDocument xDoc = new XmlDocument(); 
     xDoc.Load(strPathToXmlFile); //Physical Path of the Xml File 
     //or 
     //xDoc.LoadXml(strXmlDataString); //Loading Xml data as a String 

     //In your xml data - coverage is the root element (DocumentElement) 
     XmlNode rootNode = xDoc.DocumentElement; 

     //To get all the attributes and its values 
     //iterate thru the Attributes collection of the XmlNode object (rootNode) 
     foreach (XmlAttribute attrib in rootNode.Attributes) 
     { 
      string attributeName = attrib.Name; //Name of the attribute - x1, x2, x3 ... 
      string attributeValue = attrib.Value; //Value of the attribute 

      //do your logic here 
     } 

     //if you want to save the changes done to the document 
     //xDoc.Save (strPathToXmlFile); //Pass the physical path of the xml file 

     rootNode = null; 
     xDoc = null; 

Hoffnung, das hilft.

+0

Vielen Dank für Ihre Antwort, ich Ich wollte deinen Code ausprobieren, aber ich bekomme den Fehler "(407) Proxy Authentication Required"), ich denke (ich bin sogar ziemlich sicher), weil wir einen Proxy haben. Also, ich werde mit der vorherigen Lösung fortfahren, aber danke trotzdem für Ihre Antwort. –

Verwandte Themen