2009-07-23 84 views
2

我有幾個xml文件,其後綴不是.xml,但.component 現在我想在c#程序中處理它們,但似乎c#甚至找不到根元素的這些xml文件XmlDocument.SelectSingleNode爲根節點返回null

var doc = new XmlDocument(); 
doc.Load(path); // MG: edited to Load based on comment 
XmlNode root = doc.SelectSingleNode("rootNodename"); 

看來根目錄爲空,我應該如何處理這個問題?

+0

在這裏可能會出現多種錯誤,我懷疑這是文件擴展名。你有沒有看過調試器中的「doc」並確認它沒有加載? – womp 2009-07-23 04:02:39

+0

您可以發佈其中一個XML文件的前幾行嗎? – 2009-07-23 08:46:41

回答

5

既然你已經解決了Load/LoadXml混亂,我想到的問題是命名空間;你有沒有例子xml?與命名空間處理XML得到......「有趣」 ;-p

例如:

XmlDocument doc = new XmlDocument(); 
    doc.LoadXml(@"<test xmlns='myFunkyUri' value='abc'/>"); 
    // wrong; no namespace consideration 
    XmlElement root = (XmlElement)doc.SelectSingleNode("test"); 
    Console.WriteLine(root == null ? "(no root)" : root.GetAttribute("value")); 
    // right 
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); 
    nsmgr.AddNamespace("x", "myFunkyUri"); // x is my alias for myFunkyUri 
    root = (XmlElement)doc.SelectSingleNode("x:test", nsmgr); 
    Console.WriteLine(root == null ? "(no root)" : root.GetAttribute("value")); 

請注意,即使你的XML聲明XML別名,你可能仍然需要重新申報他們爲你命名-經理。

4

LoadXml需要一個XML字符串,而不是文件路徑。嘗試加載代替。加載不關心文件擴展名。

這裏是對機制的文檔的鏈接負載: http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.load.aspx

+0

是的,我寫了一個錯誤 其實我也試過Load(),LoadXml會生成一個異常,而Load()會加載文件沒有問題,但我找不到根節點,返回總是空 – abusemind 2009-07-23 04:13:15

0

我是有這個問題嘗試這樣的:在rootNodename 的前面放置一個破折號代替此的: XmlNode的根= doc.SelectSingleNode(「rootNodename」);

這樣做: XmlNode root = doc.SelectSingleNode(「/ rootNodename」);