2016-05-24 3 views
2

xmlファイルを解析する方法を数日間検索します。 私の問題は、ルート要素のすべてのキー値を回復したいということです。ファイルのc#を使用してルート要素のすべてのキー値を取得する方法は?

Exemple:ここ

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

が、私はすべての "報道" の値が回復することになるでしょう:x1と彼の価値、X2と彼の価値、X3と彼の値X3を... I私は見つけることができるすべてのチュートリアルで "XmlReader"を使用しようとしましたが、それでも動作しません。 私が試したことがあるすべてのチュートリアルは、特定のノード(タグ)で値を回復しますが、ルート要素のすべての値を回復することはありません。

おそらく、この同じ問題のチュートリアルは既に存在していますが、私は彼を見つけられませんでした。

ご協力いただきありがとうございます。

+0

次のWebページで再帰的なメソッドを見てください:http://stackoverflow.com/questions/28976601/recursion-parsing-xml-file-with-attributes-into-treeview-c-sharp – jdweng

答えて

1

XElementを使用して、これを行うことができます。

XElement element = XElement.Parse(input); 

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

出力

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

チェックこの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; 

・ホープ、このことができます。

+0

ありがとうございました。あなたのコードを試してみたかったが、 "(407)Proxy Authentication Required"というエラーが出る。私はプロキシを持っているからだと思う。だから、私は以前の解決策を続けますが、とにかくあなたの答えに感謝します。 –

関連する問題