2011-08-10 73 views
0

我想輸出特定的節點輸出到一個文本文件(輸出到控制檯罰款),但我不斷收到一條錯誤消息:在這條線「System.Xml.XmlNodeList」到「字符串[]」:XML輸出到文本文件?

string[] lines = elemList; 

下面是一些代碼:

namespace countC 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      XmlDocument doc = new XmlDocument(); 
      doc.Load("list.xml"); 

      XmlElement root = doc.DocumentElement; 
      XmlNodeList elemList = root.GetElementsByTagName("version"); 
      for (int i = 0; i < elemList.Count; i++) 
      { 
       Console.WriteLine(elemList[i].InnerXml); 
       string[] lines = elemList; 
       System.IO.File.WriteAllLines(@"C:\VBtest\STIGapp.txt", lines); 
      } 
      Console.ReadKey(); 
     } 
    } 
} 

回答

2

錯誤是因爲您試圖將類型爲XmlNodeList的對象分配給類型爲string[]的變量 - 兩者不兼容,您無法從另一箇中指定一個。

如果你這樣做,而不是那麼它至少會編譯:

string line = elemList[i].InnerXml; 
System.IO.File.WriteAllText(@"C:\VBtest\STIGapp.txt", line); 

雖然我不知道它會做你想要什麼(如果elemList含有較多的一個元素上面將繼續覆蓋給定文件)。

+0

好酷的工作。奇怪的是文本文件不保存循環。 – nhat

+0

@nhat這可能是'InnerXml'屬性是一個空字符串,如果元素爲空就會發生這種情況。在調試器中檢查'line'的值。 – Justin

+0

啊好的雙重檢查數據,它只保存最後一個循環。 – nhat

1

elemList是XmlNodeList中,您不能隱式將它轉換爲一個字符串數組。

你可以試試這個

string line = elemList[i].InnerText; 
System.IO.File.WriteAllLines(@"C:\VBtest\STIGapp.txt", line); 

但是這當然取決於你的數據。

+0

嗨拉斯,我想,但我得到一個錯誤信息:無法從「字符串」轉換爲「System.Collections.Generic.IEnumerable 」 我沒有嘗試選項之前,但遺憾的是沒有工作 – nhat

+0

哦對不起,WriteAllLines應該可能改爲WriteLine –

+0

真棒,謝謝! – nhat