Search code examples
c#xmlxmlreader

Trouble with XmlReader


I have never used XML much and need some help reading a complex file. enter image description here

I am trying to get to the number that is nested in: outputTree\command\heading\pivotTable\dimension\category\dimension\category\dimension\group\category\call:Text(number)

I just have no idea how to do it. if anyone could show me some basics of this it would be helpful all the examples I see are very basic and don't have this many levels so I am having issues understanding how to get to this level.

thank you.


Solution

  • You can use an XPath query. Based on the structure of your document, this should snag you the precise value you are looking for:

    var xml = XDocument.Load(@"c:\path\to\file.xml");
    var nsManager = new XmlNamespaceManager(new NameTable());
    
    nsManager.AddNamespace(
        "oms",
        "http://www.ibm.com/software/analytics/spss/xml/oms");
    
    var cell = xml.XPathSelectElement(
        "oms:outputTree/oms:command[@text='Regression']/" +
        "oms:heading[@text='uid = 1015984.00']/" +
        "oms:pivotTable[@text='Coefficients']/" +
        "oms:dimension/oms:category/oms:dimension/oms:category/" +
        "oms:dimension/oms:group/oms:category/oms:cell",
        nsManager);
    
    var number = (decimal)cell.Attribute("number");
    
    Console.WriteLine(number);
    

    Tweak as necessary. You will need these imports:

    using System.Xml.Linq;
    using System.Xml.XPath;