2015-03-31 19 views
0

當我將xmls屬性添加到我的根元素時,此代碼通過第三行的「對象引用未設置爲對象實例」的異常,但從根元素移除xmls屬性後它工作正常。使用C#XmlDocument解析Xml的錯誤類

XmlDocument xmlDoc = new XmlDocument(); 
xmlDoc.Load("file.xml");  
MessageBox.Show(xmlDoc.SelectSingleNode("person/name").InnerText); 

這裏是我的XMLFILE

<?xml version="1.0" encoding="utf-8"?> 
<person xmlns="namespace path"> 
<name>myname</name> 
</person> 

我想知道爲什麼它添加xmlns屬性,以我的根元素後不工作。我是否必須使用另一種方法進行分析?

回答

1

注意

如果XPath表達式不包含前綴,則假定 的命名空間URI是空的命名空間。如果您的XML包含 默認名稱空間,則仍然必須將前綴和名稱空間URI添加到 XmlNamespaceManager;否則,你不會選擇一個節點。 有關更多信息,請參閱使用XPath導航選擇節點。

XmlNamespaceManager ns = new XmlNamespaceManager(xmldoc.NameTable); 
ns.AddNamespace("something", "http://or.other.com/init"); 
XmlNode node = xmldoc.SelectSingleNode("something:person/name", ns); 
+1

幾乎,treemonkey:XmlNode的節點= xmldoc.SelectSingleNode( 「東西:人/名稱」,NS); – LocEngineer 2015-03-31 12:28:34

+0

對不起更新沒有使用C#太多:P – Treemonkey 2015-03-31 12:33:55

1

您需要添加命名空間使者來解決命名空間到XML文件。

考慮這個例子

XML文件

<?xml version="1.0" encoding="utf-8"?> 
    <person xmlns="http://www.findpersonName.com"> // Could be any namespace 
     <name>myname</name> 
    </person> 

,並在你的代碼

  XmlDocument doc = new XmlDocument(); 
     doc.Load("file.xml"); 

     //Create an XmlNamespaceManager for resolving namespaces. 
     XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); 
     nsmgr.AddNamespace("ab", "http://www.findpersonName.com"); 
     MessageBox.Show(doc.SelectSingleNode("//ab:name", nsmgr).InnerText); 
+0

我沒有創建這個XML文件,我不知道名稱空間,所以是否有必要命名空間應該在我的系統中。 – Raj 2015-03-31 12:42:54

+0

是的,這是必要的 – Rohit 2015-03-31 13:48:52

0

你可能要考慮使用XDocumentLinq來處理XML文檔。

下面的例子提供一個粗略的例子:

XDocument xDoc = XDocument.Load("file.xml"); 
var personNames = (from x in xDoc.Descendants("person").Descendants("name") select x).FirstOrDefault(); 

How to Get XML Node from XDocument