Search code examples
c#xml-namespacesxmldocumentxmlnode

Can't get to <style> in xml file using XmlDocument


trying to get to <style> to modify it, but I can't get any further than <layouts>, here is my code:

XmlDocument doc = new XmlDocument();
doc.Load(fi.FullName);

XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("rep", "http://developer.cognos.com/schemas/report/8.0/");

XmlNodeList nodeList = doc.SelectNodes("descendant::rep:layouts", nsmgr);

foreach (XmlNode node in nodeList)
{
    Console.WriteLine(node.Name);
    //XmlNode styleNode = node.SelectSingleNode("style");
    //if (styleNode != null)
    //    Console.WriteLine(styleNode.InnerText);

}

So, this works ("descendant::rep:layouts"), I get to see (Console.WriteLine=) "layouts". But if I try to get further, even if one node at a time, (descendant::rep:layouts/layout/reportPages/page/pageBody/contents/crosstab/style), there is no single node in the list.. please help!!! My ultimate goal is to modify the "CSS style".

XML file is below (pasted from comment):

<report xmlns= developer.cognos.com/schemas/report/8.0/">
  <queries> 
<layouts> <layout> <reportPages> 
   <page name="Page1"> <pageBody> <contents>
    <block> <contents> <block> <crosstab name="Crosstab1" refQuery="Query1"> 
    <style> 
      <CSS value="border-collapse:collapse;font-family:'Times New Roman';border:0.75pt solid black" /> <defaultStyles> 
    </style> 

Solution

  • Most likely all other nodes have some non-empty namespaces (note that empty prefix does not mean "no namespace"). One would need to see XML for better answer.

    Yes all your nodes are have "how to ignore namespaces with XPath" set as default namespace, so no nodes have it as prefix. If you want to learn more - click on "xml-namespaces" tag for details. Otherwise use following to ignore namespaces how to ignore namespaces with XPath or prefix node names with namespace prefix as you've done for layouts one:

    XmlNode styleNode = node.SelectSingleNode("rep:style", nsmgr);