2011-06-08 151 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