2016-06-15 31 views
-3

我有這段代碼,我在互聯網上發現了這個。獲取所有的XML子名

XmlDocument doc = new XmlDocument();

 doc.LoadXml("<book ISBN='1-861001-57-5'>" + 
        "<title>Pride And Prejudice</title>" + 
        "<price>19.95</price>" + 
        "</book>"); 

     XmlNode root = doc.FirstChild; 

     //Display the contents of the child nodes. 
     if (root.HasChildNodes) 
     { 
      for (int i = 0; i < root.ChildNodes.Count; i++) 
      { 
       //inner text contains the value of the childnode 
       Console.WriteLine(root.ChildNodes[i].Name); 
      } 
     } 

它的工作,但是當我從磁盤加載XML文件時,它不會給輸出。爲什麼?

string xmlText = File.ReadAllText("Filename"); 

doc.LoadXml(xmlText); 
+0

有人可以向我解釋downvote的原因嗎? – knowme

回答

0

如果您有文件路徑,則可以使用Load方法。

XmlDocument doc = new XmlDocument(); 
doc.Load("filepath"); 
+0

我已經嘗試過,但輸出仍然相同。沒有輸出 – knowme

+0

我剛剛試過用你的'Xml',它正在工作。 –

+0

你能發佈你的完整代碼嗎? –

0

試試這個。

XDocument doc = XDocument.Load(Server.MapPath("yourfile.xml"));//Load file from disk 
var NodeNames = doc.Descendants("book").Elements().Select(x => x.Name.LocalName).ToList(); 

你將不得不如果你的文件駐留inside folder指定文件夾的path

相關問題