2011-06-08 159 views
1

查詢XML文檔我有一個看起來像一個XML文件中的一個片段:與命名空間

<?xml version="1.0" encoding="utf-16"?> 
<ArrayOfCatalogItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <CatalogItem> 
     <ID xmlns="http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices">bbe9b897-5d3b-4340-914b-fce8d6022bd9</ID> 
     <Name xmlns="http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices">EmployeeReport</Name> 
    </CatalogItem> 

現在我想要查詢該文件的所有名稱的元素。我知道我可以使用SelectNodes("//Name")來給我我想要的東西。但是,由於我在<ArrayOfCatalogItem>中有名稱空間,所以我必須對此進行說明。因此,這裏是我到目前爲止的代碼:

System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); 
doc.Load(@"C:\CatalogItems.xml"); 

// Create an XmlNamespaceManager for resolving namespaces 
System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(doc.NameTable); 
nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); 
nsmgr.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema"); 

System.Xml.XmlNodeList nodeList; 
System.Xml.XmlNode root = doc.DocumentElement; 

nodeList = root.SelectNodes("//Name", nsmgr); 
Console.WriteLine("There are {0} items.", nodeList.Count); 
foreach (System.Xml.XmlNode item in nodeList) 
{ 
    Console.WriteLine(item.InnerText); 
} 

不過,我遇到的問題是在<Name>標籤的命名空間的定義。我如何查詢文檔中的所有Name值,並考慮每個<Name>的名稱空間定義爲屬性?

回答

1

您使用了錯誤的XML命名空間 - 你需要使用應用到<Name>標籤之一 - 而不是文件默認命名(xsd:xsi:前綴)。

試試這個:

using System.Xml; 

XmlDocument doc = new XmlDocument(); 
doc.Load(@"C:\CatalogItems.xml"); 

// Create an XmlNamespaceManager for resolving namespaces 
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); 
nsmgr.AddNamespace("rs", "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices"); 

XmlNodeList nodeList; 
XmlNode root = doc.DocumentElement; 

nodeList = root.SelectNodes("//rs:Name", nsmgr); 

Console.WriteLine("There are {0} items.", nodeList.Count); 

foreach (XmlNode item in nodeList) 
{ 
    Console.WriteLine(item.InnerText); 
} 
+0

這工作。但是,在代碼中使用AddNamespace時,第一個參數是「rs」。但是這不是在文檔中的任何地方定義的。它確實有效,但現在我不明白爲什麼它能正常工作。 – coson 2011-06-08 19:05:49

+0

@Coson:這只是一個**任意的** XML命名空間前綴,您在代碼中定義** ** - 它與該文檔具有**無關** - 只是**您的方式**在**中你的代碼**爲XML命名空間定義一個前綴。當然,**必須匹配的唯一事物就是實際的XML名稱空間!但前綴是完全獨立於底層的XML文檔... – 2011-06-08 19:08:05

+0

工作。起初,我最初對AddNamespace方法的第一個參數感到困惑,因爲我沒有在文檔的任何位置看到「rs」。所以我猜你可以使用任何你想要的東西,因爲命名空間沒有被指定。通過在這兩個地方將「rs」更改爲「test」,似乎可行。 – coson 2011-06-08 19:08:43