【发布时间】:2011-09-25 09:49:57
【问题描述】:
我有一个 XML 文件的 sn-p,如下所示:
<?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>
现在我正在尝试在文件中查询所有 Name 元素。我知道我可以使用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 值?
【问题讨论】:
标签: xml