1

I have the following XML (only part of it, can't share it all as its confidential):

<?xml version="1.0" encoding="utf-8"?>
<Report xsi:schemaLocation="Aircraft_SpecSheetDetails" Name="Aircraft_SpecSheetDetails" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="Aircraft_SpecSheetDetails">
    <Aircraft_SpecSheet_SUB_SpecificData>
        <Report Name="Aircraft_SpecSheet_SUB_SpecificData">
            <table8 Textbox29="No">
                <Detail_Collection>
                    <Detail OperWeightType_Description="Maximum Landing Weight" AcrftOperWeight_Current_KG="43000" AcrftOperWeight_Current_LBS="94799" />
                    <Detail OperWeightType_Description="Maximum Take Off Weight" AcrftOperWeight_Current_KG="50300" AcrftOperWeight_Current_LBS="110893" />
                    <Detail OperWeightType_Description="Maximum Zero Fuel Weight" AcrftOperWeight_Current_KG="40800" AcrftOperWeight_Current_LBS="89949" />
                    <Detail OperWeightType_Description="Basic Empty Weight" AcrftOperWeight_Current_KG="27841" AcrftOperWeight_Current_LBS="61379" />
                </Detail_Collection>
            </table8>
        </Report>
    </Aircraft_SpecSheet_SUB_SpecificData>
</Report>

I want to grab the Detail element with a specific value in the OperWeightType_Description attribute.

My XPath looks like this: //Detail[@OperWeightType_Description='Maximum Landing Weight']

It works using this tool: https://www.freeformatter.com/xpath-tester.html

But in C#, the code below doesn't work - the weightNode remains NULL.

private int? ImportWeightValue(XmlNode report, string weightDescription)
{
    XmlNode weightNode = report.SelectSingleNode($"//Detail[@OperWeightType_Description='{weightDescription}']");

    if (weightNode != null)
    {
        return weightNode.ReadInt("AcrftOperWeight_Current_KG");
    }

    return null;
}

The report XmlNode in the parameter is the DocumentElement -- the <Report> element of the XML.

MartinHN
  • 19,542
  • 19
  • 89
  • 131
  • 1
    Well you've got a default namespace, `xmlns="Aircraft_SpecSheetDetails"`, so see [XmlDocument.SelectSingleNode and xmlNamespace issue](https://stackoverflow.com/questions/4171451/xmldocument-selectsinglenode-and-xmlnamespace-issue) and also [Using Xpath With Default Namespace in C#](https://stackoverflow.com/questions/585812/using-xpath-with-default-namespace-in-c-sharp). – dbc Jul 28 '17 at 22:21
  • @dbc Works now - put it into an answer if you want the points! – MartinHN Jul 28 '17 at 22:25

0 Answers0