2015-09-22 61 views
0

你好,今天我想知道如何以下面的方式讀取一個xml文件,我還沒有找到任何像這樣或anythig simulaur如何我想這樣做這樣可行。我有一個xml文件,下面的內容格式在此之下被禁用。從桌面上的文件讀取xml數據

<smallusers> 
<user id="1"> 
<name>John</name> 
<motto>I am john, who are you?</motto> 
</user> 
<user id="2"> 
<name>Peter</name> 
<motto>Hello everyone!</motto> 
</user> 
</smallusers> 
<bigusers> 
<user id="3"> 
<name>Barry</name> 
<motto>Earth is awesome</motto> 
</user> 
</bigusers> 

我怎樣才能將它放入在csharp的2名名單

+0

你想在每個列表中放什麼? –

回答

0
  1. 加載它作爲一個文本文件轉換成一個字符串或StringBuilder的。
  2. 與<XML>前綴,它與<結束它/ XML >
  3. 然後使用XmlDocument的加載你的XML
+0

爲什麼你會建議使用XmlDocument而不是XDocument? LINQ to XML比XmlDocument,IMO更*更友好。 –

+0

使用您的Xml文檔管理器的選擇:) – Brian

0

XML只能有一個根標籤。您輸入的根目錄不止一個。所以你必須把你的XML包裝成類似下面的代碼

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.IO; 
using System.Xml; 
using System.Xml.Linq; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     const string FILENAME = @"c:\temp\test.txt"; 
     static void Main(string[] args) 
     { 
      string input = File.ReadAllText(FILENAME); 

      input = string.Format("<Root>{0}</Root>", input); 

      XElement root = XElement.Parse(input); 

     } 
    } 
} 
​