I have a snippet of an XML file that looks like:
<?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>
Now I'm trying to query the file for all the Name elements. I'm aware that I can use the SelectNodes("//Name")
to give me what I want. However, since I have namespaces in the <ArrayOfCatalogItem>
I have to account for that. So here's the code I have so far:
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);
}
However, the problem I'm having is the namespace definitions in the <Name>
tag. How would I query the document for all Name values taking into account each <Name>
has a namespace defined as an attribute?
You're using the wrong XML namespace - you need to use the one that is applied to the <Name>
tag - not the document default namespaces (xsd:
and xsi:
prefixes).
Try this:
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);
}
精彩评论