user3574500
user3574500

Reputation: 1

Using SelectSingleNode with XML file, node repeats twice

Here's a file I'm trying to parse. I can get data from <countryName> and <countryAbbrev>, but getting an error when trying to read <gml:name> node. Note that this node appears twice in XML file, on the top level and under <Hostip> node. Here's a syntax I'm using:

Any ideas?

<HostipLookupResultSet xmlns:gml="http://www.opengis.net/gml" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0.1" 
 xsi:noNamespaceSchemaLocation="http://www.hostip.info/api/hostip-1.0.1.xsd">
    <gml:description>This is the Hostip Lookup Service</gml:description>
    <gml:name>hostip</gml:name>
    <gml:boundedBy>
        <gml:Null>inapplicable</gml:Null>
    </gml:boundedBy>
    <gml:featureMember>
        <Hostip>
            <ip>24.205.216.31</ip>
            <gml:name>Carson City, NV</gml:name>
            <countryName>UNITED STATES</countryName>
            <countryAbbrev>US</countryAbbrev>
            <ipLocation>
                <gml:pointProperty>
                    <gml:Point srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">
                        <gml:coordinates>-119.763,39.233</gml:coordinates>
                    </gml:Point>
                </gml:pointProperty>
            </ipLocation>
        </Hostip>
    </gml:featureMember>
</HostipLookupResultSet>

Upvotes: 0

Views: 197

Answers (1)

StuartLC
StuartLC

Reputation: 107237

You will need to use an XmlNamespaceManager for the xmlns alias gml. Try like so:

XmlNamespaceManager nsmanager = new XmlNamespaceManager(doc.NameTable);
nsmanager.AddNamespace("gml", "http://www.opengis.net/gml");

Debug.WriteLine(doc.SelectSingleNode("//countryName").InnerText);
foreach (XmlNode node in doc.SelectNodes("//gml:name", nsmanager))
{
    Debug.WriteLine(node.InnerText);
}

Result:

UNITED STATES 
hostip 
Carson City, NV

Edit

Just a thought, if you are trying to access just one of the gml:name nodes, the following xpaths will navigate a subtree for the first and second respectively:

//HostipLookupResultSet/gml:name/text()
//HostipLookupResultSet/gml:featureMember/gml:name/Hostip/text()

Upvotes: 1

Related Questions