开发者

XPath and SelectNodes Method

开发者 https://www.devze.com 2023-02-09 15:55 出处:网络
First I did see this but it did not seem to help XPath SelectNodes in .NET I am trying to read a SSRS report defination.

First I did see this but it did not seem to help XPath SelectNodes in .NET

I am trying to read a SSRS report defination.

ReportingService report = new ReportingService();
report.Credentials = System.Net.CredentialCache.DefaultCredentials;

string x = new System.Text.UTF8Encoding().GetString( 
                           report.GetReportDefinition(ReportName));

//Remove a Character at the beginning of the document -- Char 65279
x = x.Replace(x.Substring(0, 1), "");
XmlDocument xml = new XmlDocument();

XmlNamespaceManager ns = new XmlNamespaceManager(xml.NameTable);
// This appears to be a reserved default?
//ns.AddNamespace("xmlns","http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition");
ns.AddNamespace("xmlns:rd","http://schemas.microsoft.com/SQLServer/reporting/reportdesigner");
xml.LoadXml(x);

Now I am looking for the Query node which should be under

Report
...
    DataSets 
        DataSet
            Query

Now if I look at some variables

  xml.Name = "#document"
  xml.DocumentElement.Name = "Report"
  xml.DocumentElement.ChildNodes[12].Name = "DataSets"
  xml.DocumentElement.ChildNodes[12].ChildNodes[0].Name = "DataSet"
  xml.DocumentElement.ChildNodes[12].ChildNodes[0].ChildNodes[1].Name = "Query"

But the problem is trying a couple of things I can not get to this DataSets Node or any subnodes. Example

 xml.DocumentElement.SelectNodes(".//DataSets",ns);
 xml.DocumentElement.SelectNodes("DataSets",ns);
 xml.SelectSingleNode("//Report/DataSets",ns);
 xml.SelectSingleNode("//Query",ns);

Both return null 开发者_高级运维what am I doing wrong.

Edited using driis advice


Thank you guys for leading me down the right path, this also helped Using xpath and rdlc report

So the answer is this, you can name your prefixes anything you want. Uncommenting out the line

ns.AddNamespace("xmlns","http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition");

and changing it to

ns.AddNamespace("def","http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition");

Then the following works

 xml.SelectNodes("//def:DataSets",ns);
 xml.SelectSingleNode("//def:Report/def:DataSets", ns);
 xml.SelectSingleNode("//def:Query", ns);


this shall return you all DataSets nodes in the xml XmlDocument:

xml.SelectNodes("//DataSets");

Note that this returns a XmlNodeList as a type on which you can iterate.

If you are sure the problem has to do with namespaces, have a look at http://support.microsoft.com/kb/318545


Then why don't you just do

XmlNodeList queries =  xml.SelectNodes("//Query");
//selects 'Query' node occuring anywhere

foreach(XmlNode query in queries){
  XmlNode dataSetForquery = query.GetParent();

  //do some other stuff with query here
}
0

精彩评论

暂无评论...
验证码 换一张
取 消