Home > Blockchain >  How to select child node with XPath
How to select child node with XPath

Time:11-09

I'm trying to get values from a XML document using the iXF format, but I'm having some issues with the XPath syntax.

I have the following XML document

<SOAP_ENV:Envelope xmlns:NS2="http://www.ixfstd.org/std/ns/core/classBehaviors/links/1.0" xmlns:NS1="CATIA/V5/Electrical/1.0" xmlns:tns="IXF_Schema.xsd" xmlns:ixf="http://www.ixfstd.org/std/ns/core/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP_ENV="http://schemas.xmlsoap.org/soap/envelope/" xsi:schemaLocation="IXF_Schema.xsd ElectricalSchema.xsd">
    <SOAP_ENV:Body>
        <ixf:object id="Electrical Physical System00000089.1" xsi:type="tns:Harness">
            <tns:Name>Electrical Physical System00000089.1</tns:Name>
        </ixf:object>
        <ixf:object id="X10(1)//X11(1)" xsi:type="tns:Wire">
            <tns:Name>X10(1)//X11(1)</tns:Name>
            <NS1:Wire>
                <NS1:Length>763,752mm</NS1:Length>
                <NS1:Color>RD</NS1:Color>
                <NS1:OuterDiameter>1,32mm</NS1:OuterDiameter>
            </NS1:Wire>
        </ixf:object>
    </SOAP_ENV:Body>
</SOAP_ENV:Envelope>

And i'm trying to find all the Wire objects and get the Name and Length values with the following code.

XmlDocument xlDocument = new XmlDocument();
xlDocument.Load(importFile);

XmlNamespaceManager nsManager = new XmlNamespaceManager(xlDocument.NameTable);
nsManager.AddNamespace("tns", "IXF_Schema.xsd");
nsManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
nsManager.AddNamespace("ixf", "http://www.ixfstd.org/std/ns/core/1.0");
nsManager.AddNamespace("NS1", "CATIA/V6/Electrical/1.0");
nsManager.AddNamespace("NS2", "http://www.ixfstd.org/std/ns/core/classBehaviors/links/1.0");
             
//Get all wire objects
XmlNodeList wires = xlDocument.SelectNodes("descendant::ixf:object[@xsi:type = \"tns:Wire\"]", nsManager);

foreach (XmlNode wire in wires)
{
    string wireName;
    string wireLength;

    XmlNode node = wire.SelectSingleNode("./tns:Name", nsManager);
    wireName = node.InnerText;
    
    XmlNode node1 = wire.SelectSingleNode("./NS1:Wire/NS1:Length", nsManager);            
    wireLength = node1.InnerText;
}

I can get the wireName value without any problems but the Length element selection always returns 0 matches and I can not figure out why. I also tried to only select the Wire element using the same syntax as the Name element ./NS1:Wire but that also returns 0 matches.

CodePudding user response:

Your XML declares xmlns:NS1="CATIA/V5/Electrical/1.0", your C# declares a different namespace nsManager.AddNamespace("NS1", "CATIA/V6/Electrical/1.0"), make sure both namespaces match exactly.

  • Related